Reputation: 1699
I want to have a python command line argument --lambda
, but I can't access it as lambda is a python keyword.
import argparse
p = argparse.ArgumentParser()
p.add_argument('--lambda')
args = p.parse_args()
print args.lambda
I get:
print args.lambda
^
SyntaxError: invalid syntax
How can I do this?
Upvotes: 2
Views: 353
Reputation: 231605
argparse
uses hasattr
and getattr
to set values in the Namespace. This allows you to use flags/dest that are not valid in the args.dest
syntax. Here the problem is with a restricted key word. It could also be a string with special characters. So getattr(args, 'lambda')
should work.
vars(args)
creates a dictionary, allowing you to use vars(args)['lambda']
.
But changing the dest is a cleaner solution. That's part of why that parameter is allowed.
(For a positional argument, choose a valid dest right away.)
Upvotes: 1
Reputation: 1699
You can add a different name for the attribute with dest
e.g.
import argparse
p = argparse.ArgumentParser()
p.add_argument('--lambda', dest='llambda')
args = p.parse_args()
print args.llambda
Upvotes: 4