我正在尝试使用argh库将参数列表传递给Python脚本。希望能够接受以下类型的输入:
./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只接受第一个参数,并将其视为字符串。我该如何使它“期望”整数列表?
我看到在optparse中如何实现,但是对于(未弃用的)argparse呢?或者使用argh更好的装饰语法?这些似乎更符合Python风格。
func(argA, *argB)
(尽管*args
映射到nargs='*'
而不是nargs='+'
)。 - Andy Mikhaylenkoparser.add_argument('-a', '--arg', type=lambda s: [int(n) for n in s.split()])
并使用引号调用脚本:python test.py --arg="1 2 3"
。 - jcollado=
字符。-a 1 2
的意思是“a = [1, 2]”,而-a=1 2
的意思是“a = 1; some-positional-argument = 2”。 - Andy Mikhaylenko