pythonargparse

How to read argparser values from a config file in Python?


I have a lot of arguments for my script. And along with the argparser, I want users to also have the option to specify those arguments via a config file.

parser.add_argument('-a','--config_file_name' ...required=False)
parser.add_argument('-b' ...required=True)
parser.add_argument('-c' ...required=False)
....

At this point I just need the logic to implement the following:

How can this be achieved?


Solution

  • I don't think this is up to argparse to handle. Argparse simple needs to check if the argument for the config file is there and pass it on to your program.

    You need to handle this in your program, which would mean doing something like:

    ...
    arguments=parser.parse_args()
    if len(arguments.config_file_name):
        f=fopen(arguments.config_file_name,'rb')
        conf_settings = f.read()
        for line in conf_settings:
            #parse your config format here.
    

    this way, if the config_file_name is set, you will overwrite any possible given arguments, and if not, the program will be executed with the arguments specified by the user.

    for example:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("a")
    args = parser.parse_args()
    if args.a:
        #We're getting config from config file here...
    else:
        #We're getting config from the command line arguments
    #Now we can call all functions with correct configuration applied.