5

I want to add an argument named 'print' to my argument parser

arg_parser.add_argument('--print', action='store_true', help="print stuff")
args = arg_parser.parse_args(sys.argv[1:])
if args.print:
    print "stuff"

Yields:

if args.print:
            ^
SyntaxError: invalid syntax

1 Answer 1

11

You can use getattr() to access attributes that happen to be reserved keywords too:

if getattr(args, 'print'):

However, you'll make it yourself much easier by just avoiding that name as a destination; use print_ perhaps (via the dest argument):

arg_parser.add_argument('--print', dest='print_', action='store_true', help="print stuff")
# ...
if args.print_:

or, a more common synonym like verbose:

arg_parser.add_argument('--print', dest='verbose', action='store_true', help="print stuff")
# ...
if args.verbose:

Quick demo:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--print', dest='print_', action='store_true', help="print stuff")
_StoreTrueAction(option_strings=['--print'], dest='print_', nargs=0, const=True, default=False, type=None, choices=None, help='print stuff', metavar=None)
>>> args = parser.parse_args(['--print'])
>>> args.print_
True
1
  • Using 'dest' to store the value is ingenious, I read the argparse documentation three times over and could just not figure it out. I will accept this as an answer once it's possible.
    – crunsher
    Jul 27, 2015 at 14:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.