Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse argument named "print"

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
like image 653
crunsher Avatar asked Jul 27 '15 14:07

crunsher


People also ask

What does parse_args return?

Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.


1 Answers

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
like image 197
Martijn Pieters Avatar answered Oct 01 '22 14:10

Martijn Pieters