简体   繁体   中英

How to to extract data from ConfigParser

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)

This is the right answer to the question.

I found out that configuration files have section, with each section led by a section header, like this [SECTION] , but my code in looking for a [DEFAULT] section which does not exist in the configuration file, rather it contains an [ARGUMENT] section header, instead of a [DEFAULT] .

Here is the the config file should look like:

[DEFAULT]
n1=5
n2=7

Here is the right code to get config data:

NOTE: Code is fine, nothing was changed

...
...
...

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM