I'd like to put be able launch python's scripts from the shell command line in a following manner:
python script_name -temp=value1 -press=value2
I wrote sth like that:
#!/usr/bin/python
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("temp", help="specify the temperature [K]", type=float)
parser.add_argument("press", help="specify the pressure [Pa]", type=float)
args = parser.parse_args()
temp = args.temp
press = args.press
print temp
print press
And the imput can be:
python script_name value1 value2
How to be able to enter the values in manner -arg=value ?
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .
*args allows us to pass a variable number of non-keyword arguments to a Python function. In the function, we should use an asterisk ( * ) before the parameter name to pass a variable number of arguments.
Use parser.add_argument("--temp", ...)
There are great examples in the argparser manual:
http://docs.python.org/2.7/library/argparse.html
Edit:
For arguments starting with -
only the pattern -argument VALUE
works.
This works also for arguments starting with --
, but here you can also use the pattern --argument=VALUE
.
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