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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值