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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With