2

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And '-h' now works as well! I think I got confused when the examples moved from "print parser.parse_args([ '-t']" to actually using it in the script.
2

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()

Comments

1

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

1 Comment

This is explained in the documentation: Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line arg. In this case the value from const will be produced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.