argparse - specify order of argument parsing?
Tim Chase
python.list at tim.thechases.com
Sat Aug 31 13:50:16 EDT 2013
On 2013-08-31 13:11, 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.
While I haven't come up with a good solution using argparse/optparse
alone, I've found that it's easier (for processing) to specify the
config file as an environment variable. So rather than doing
my_prog.py -c /path/to/config.ini arg1 arg2 ...
I just do
MY_PROG_CONF=/path/to/config.ini my_prog.py arg1 arg2 ...
...at least on *nix systems; on Win32, it's
c:\temp> set MY_PROG_CONF=c:\path\to\config.ini
c:\temp> python my_prog.py arg1 arg2 ...
Then you just intercept the config-file name from os.environ:
config_file = os.environ.get(
"MY_PROG_CONF",
default_ini_location)
-tkc
More information about the Python-list
mailing list