import sys
def fun( a=7, b=1 ):
print a, b
fun()
fun( a=5 )
fun( sys.argv[1:] )
The first fun() prints out '7,1', the second prints out '5,1', but the third prints out '['a=8', 'b=6'] 1]'. I would like to be able to call my program with
python my_program.py a=5 b=6
to change the value of the printed a and b. But this doesn't work since sys.argv[1] is a list of strings.
Is there any way to convert the the string list to a form the function can understand?
Use **
for kwarg unpacking:
d = {}
for a in sys.argv[1:]:
k, v = a.split('=')
d[k] = int(v)
func(**d)
Another way, using the csv
module:
import csv
func(**{k: int(v) for k, v in csv.reader(sys.argv[1:], delimiter='=')})
As @MartijnPieters noted you may use the argparse
module
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-a', type=int)
parser.add_argument('-b', type=int)
args = parser.parse_args()
fun(**dict(args._get_kwargs()))
but then you have to adjust the way you input your arguments
Use *
to unpack a list into arguments:
fun(*sys.argv[1:])
Note that this will result in string arguments; sys.argv
command line entries are always strings.
You may want to look into the argparse
module to handle command line arguments for you, including automatic conversion:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-a', type=int, default=7)
parser.add_argument('-b', type=int, default=1)
args = parser.parse_args()
func(args.a, args.b)
Then use:
$ python my_program.py -a=5 -b=6
The added advantage here is that you get proper help feedback, and you follow standard command-line conventions:
$ python my_program.py --help
usage: [-h] [-a A] [-b B]
Process some integers.
optional arguments:
-h, --help show this help message and exit
-a A
-b B
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.