Quantcast
Channel: Active questions tagged config - Stack Overflow
Viewing all articles
Browse latest Browse all 5049

How to to extract data from ConfigParser

$
0
0

I'm building a cron job and data has to be read from a configuration file. I'm using the Python ConfigParser module to achieve this, but I can't seem to read the data using the command-line argument and sub-command. I'm using Python argparse module for command-line argument and sub-command. Help please.

Here is the configuration file:

[ARGUMENTS]
n1=5
n2=7

Here is the code that does the work:

import argparse
import sys
import configparser

def main(number, other_number):
    result = number * other_number
    print(f'The result is {result}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Running Cron Job...')
    parser.add_argument('-n1', type=int, help='A number', default=1)
    parser.add_argument('-n2', type=int, help='Another number', default=1)

    parser.add_argument('--config', '-c', type=argparse.FileType('r'), help='config file')

    args = parser.parse_args()

    if args.config:
        config = configparser.ConfigParser()
        config.read_file(args.config)

        # Transform values into integers
        args.n1 = int(config['DEFAULT']['n1'])
        args.n2 = int(config['DEFAULT']['n2'])
    main(args.n1, args.n2)

Viewing all articles
Browse latest Browse all 5049

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>