Domanda

Ho una funzione:

def x(a,b,c)

Come faccio a raccogliere i valori delle variabili dalla riga di comando che si adattano questo schema?

python test.py --x_center a --y_center b c (c ha, per esempio, 3, 4 o più valori)

È stato utile?

Soluzione

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 floats. 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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top