I have been googling almost an hour and am just stuck.
for a script, stupidadder.py, that adds 2 to the command arg.
e.g. python stupidadder.py 4
prints 6
python stupidadder.py 12
prints 14
I have googled so far:
import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('x', metavar='x', type=int, nargs='+', help='input number') ... args = parser.parse_args() print args x = args['x'] # fails here, not sure what to put print x + 2
I can't find a straightforward answer to this anywhere. the documentation is so confusing. :( Can someone help? Please and thank you. :)
To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
Python Command line arguments are input parameters passed to the script when executing them. Almost all programming language provide support for command line arguments. Then we also have command line options to set some specific options for the program.
Assuming that you are learning how to use the argparse module, you are very close. The parameter is an attribute of the returned args object and is referenced as x = args.x
.
import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('x', metavar='x', type=int, nargs='+', help='input number') ... args = parser.parse_args() print args #x = args['x'] # fails here, not sure what to put x = args.x print x + 2
A sample run in Ipython with your code, showing that args is a simple object, not a dictionary. In the argparse code the namespace is accessed with getattr
and setattr
In [4]: args=parser.parse_args(['12','4','5']) In [5]: args Out[5]: Namespace(x=[12, 4, 5]) In [6]: args['x'] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-3867439e1f91> in <module>() ----> 1 args['x'] TypeError: 'Namespace' object is not subscriptable In [7]: args.x Out[7]: [12, 4, 5] In [8]: getattr(args,'x') Out[8]: [12, 4, 5] In [9]: sum(getattr(args,'x')) Out[9]: 21
vars()
can be used to turn the namespace into a dictionary.
In [12]: vars(args)['x'] Out[12]: [12, 4, 5]
Review the Namespace section of the argparse documentation.
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