最佳答案
我试图使用 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 更好的修饰语法?这些看起来更像蟒蛇。