argparse - specify order of argument parsing?

Peter Otten __peter__ at web.de
Sun Sep 1 02:53:10 EDT 2013


Eduardo Alvarez wrote:

> When using argparse, is there a way to specify in what order arguments
> get parsed? I am writing a script whose parameters can be modified in
> the following order:
> 
> Defaults -> config file -> command-line switches.
> 
> However, I want to give the option of specifying a config file using a
> command line switch as well, so logically, that file should be parsed
> before any other arguments are applied. However, it seems that
> parse_args() parses arguments in the order they're given, so if the
> config file switch is not given first, the config file will overwrite
> whatever was in the command-line switches, which should have higher
> priority.
> 
> Thank you in advance,

If you use 

http://docs.python.org/dev/library/argparse.html#fromfile-prefix-chars

to read the configuration file it should be obvious to the user that the 
order is significant. You can even construct multiple config files with 
partially overlapping options:

$ cat load_options.py
import argparse

parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
parser.add_argument("--infile")
parser.add_argument("--outfile")
parser.add_argument("--logfile")

print(parser.parse_args())
$ cat option1.txt
--infile=alpha.txt
--outfile=beta.txt
$ cat option2.txt
--outfile=GAMMA.txt
--logfile=DELTA.txt
$ python load_options.py @option1.txt @option2.txt
Namespace(infile='alpha.txt', logfile='DELTA.txt', outfile='GAMMA.txt')
$ python load_options.py @option2.txt @option1.txt
Namespace(infile='alpha.txt', logfile='DELTA.txt', outfile='beta.txt')

If you insist you could modify the argument list with the following hack:

sys.argv[1:] = sorted(sys.argv[1:], key=lambda arg: arg.startswith("@"), 
reverse=True)

There might also be a way to utilize parse_known_args().




More information about the Python-list mailing list