Optional Command Line Parameter in Python
-
26-10-2019 - |
Pergunta
I am trying to retrieve optional command line parameters for a Python script (2.7 under Windows) and things are not going smoothly. The code is:
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', default = 'baz')
args = parser.parse_args(['-t'])
print args.t
If I run "program.py
" with no parameter, args.t is printed as None.
If I run "program.py -t
", args.t is printed as None.
If I run "program.py -t foo
", args.t is printed as None.
Why am I not getting the value from the command line into args.t?
Solução
Don't pass ['-t']
to parse_args. Just do:
args = parser.parse_args()
Any arguments you pass to parse_args are used instead of your command-line. So with that argument it doesn't matter what command-line you use, argparse never sees it.
Outras dicas
The line
args = parser.parse_args(["-t"])
is passing the command line arguments ["-t"] to the parser. You want to work with the actual command line arguments, so change the line to
args = parser.parse_args()
Use the const keyword argument:
import argparse
parser = argparse.ArgumentParser(description = 'Process display arguments')
parser.add_argument('-t', nargs = '?', const = 'baz', default = 'baz')
args = parser.parse_args()
print args.t
Running it yields:
% test.py # handled by `default`
baz
% test.py -t # handled by `const`
baz
% test.py -t blah
blah