Reputation: 788
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)
Upvotes: 1
Views: 563
Reputation: 788
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)
Upvotes: 1