python argh/argparse:如何将列表作为命令行参数传递?

Abe*_*Abe 64 python command-line-arguments argparse argh

我正在尝试使用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 
Run Code Online (Sandbox Code Playgroud)

我的内部代码如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

这是它的行为方式:

$ 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
Run Code Online (Sandbox Code Playgroud)

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

在optparse中看到了这是怎么做的,但是(未弃用的)argparse呢?或者使用argh更好的装饰语法?这些似乎更加pythonic.

jco*_*ado 85

argparse,你只需使用type=int

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', '--arg', nargs='+', type=int)
print parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

示例输出:

$ python test.py -a 1 2 3
Namespace(arg=[1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

编辑:我不熟悉argh,但它似乎只是一个包装argparse,这对我有用:

import argh

@argh.arg('-a', '--arg', nargs='+', type=int)
def main(args):
    print args

parser = argh.ArghParser()
parser.add_commands([main])
parser.dispatch()
Run Code Online (Sandbox Code Playgroud)

示例输出:

$ python test.py main -a 1 2 3
Namespace(arg=[1, 2, 3], function=<function main at 0x.......>)
Run Code Online (Sandbox Code Playgroud)