I have a function:
def x(a,b,c)
How can I collect variable values from the command line that fit this pattern?
python test.py --x_center a --y_center b c
(c
has, for example, 3, 4 or more values )
The Python argparse library was released as part of the standard library with Python 3.2 on February the 20th, 2011. It was introduced with Python Enhancement Proposal 389 and is now the standard way to create a CLI in Python, both in 2.7 and 3.2+ versions.
The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.
In addition to this, the Python argparse library is part of the Python standard library and therefore needs no installation. Sometimes you may come across programs that run specifically in the terminal using the python keyword followed by the name of the file.
You can do something like that like this:
import argparse
def x(x_center, y_center, values):
print "X center:", x_center
print "Y center:", y_center
print "Values:", values
def main():
parser = argparse.ArgumentParser(description="Do something.")
parser.add_argument('-x', '--x-center', type=float, required=True)
parser.add_argument('-y', '--y-center', type=float, required=True)
parser.add_argument('values', type=float, nargs='*')
args = parser.parse_args()
x(args.x_center, args.y_center, args.values)
if __name__ == '__main__':
main()
Try it out:
$ python test.py --x-center 1 --y-center 2 3 4 5
X center: 1.0
Y center: 2.0
Values: [3.0, 4.0, 5.0]
To use the argparse
module, you'll normally want to start with a main
function (and some boilerplate that calls it). In the main
function, you'll want to create an ArgumentParser
. After that, you'll want to add some arguments.
To add an argument, you use add_argument
.
parser.add_argument('-x', '--x-center', type=float, required=True)
Here, we're adding an option, -x
, which also has a long option variant, --x-center
. The type
we pass to add_argument
tells it to require it to be a float
(and error if it's not a valid float). We also tell argparse
that it's required; if it's not provided, error.
parser.add_argument('values', type=float, nargs='*')
This is just like before, but since the string we pass to it does not begin with a dash, it assumes it is not an option, but rather a non-option argument. Again, we tell it we want float
s. nargs
allows you to specify that it takes more than one argument. *
specifies that we want any amount of arguments.
Finally, we parse the command line with parse_args
. This returns an object that we'll store.
You can then access the options and arguments on that args
object and do relevant things in your program.
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