Search code examples
pythonpython-3.xcmdconfigconfigparser

Python project through cmd with different config files


i want to start my python project through a cmd window with different configurations, e.g the function that need different parameter:

download.rawData.download(starttime=starttime, endtime=endtime)

the starttime and endtime values are from a configfile: (config1.cfg)

[Parameter]
starttime=Monday
endtime=Tuesday

config2.cfg:

[Parameter]
starttime=tuesday
endtime=friday

What is the best way to start the project from the cmd like:

Python3 project.py --config1 //for time X
Python3 project.py --config2 //for time Y

...and so on, of course there are different start and endtimes declared in the config file

The goal is that the configurations for the start- and endtime are not hard-coded in the main project.

What I tried until now:

commandLineArgumentParser: ArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-config1", "--config1", help="Config file 1")
commandLineArgumentParser.add_argument("-config2", "--config2", help="Config file2")
commandLineArguments = commandLineArgumentParser.parse_args()
config1= commandLineArguments.odessa


starttime = config['Parameter']['starttime']
endtime = config['Parameter']['endtime']

But this didn´t work Anyone has an idea?

Thanks a lot!


Solution

  • You wouldn't need to run the script multiple times for each parameter. Simply use the configparser module to parse your config file, which you specify on the command line (via the argparse module):

    import argparse
    import configparser
    
    parser = argparse.ArgumentParser()
    parser.add_argument('config', help="Config file to parse")
    
    args = parser.parse_args()
    
    config = configparser.ConfigParser()
    config.read(args.config)
    config.sections()  # Returns ['Parameter']
    
    start = config['Parameter']['starttime']
    end = config['Parameter']['endtime']