python add argument list_python argh/argparse:我如何传递一个列表作为命令行参数?

我试图传递一个参数列表到python脚本使用argh库。可以接受这样的输入的东西:

./my_script.py my-func --argA blah --argB 1 2 3 4

./my_script.py my-func --argA blah --argB 1

./my_script.py my-func --argA blah --argB

我的内部代码如下所示:

import argh

@argh.arg('--argA', default="bleh", help='My first arg')

@argh.arg('--argB', default=[], help='A list-type arg--except it\'s not!')

def my_func(args):

"A function that does something"

print args.argA

print args.argB

for b in args.argB:

print int(b)*int(b) #Print the square of each number in the list

print sum([int(b) for b in args.argB]) #Print the sum of the list

p = argh.ArghParser()

p.add_commands([my_func])

p.dispatch()

下面是它的行为:

$ python temp.py my-func --argA blooh --argB 1

blooh

['1']

1

1

$ python temp.py my-func --argA blooh --argB 10

blooh

['1', '0']

1

0

1

$ python temp.py my-func --argA blooh --argB 1 2 3

usage: temp.py [-h] {my-func} ...

temp.py: error: unrecognized arguments: 2 3

问题似乎很简单:argh只接受第一个参数,并将其视为字符串。我如何让它“期望”一个整数列表?

我看到how this is done in optparse,但是(不是过时的)argparse呢?或者使用argh的更好的装饰语法?这些似乎更多的pythonic。

你可能感兴趣的:(python,add,argument,list)