本文介绍了python argh/argparse:如何将列表作为命令行参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 argh 库将参数列表传递给 python 脚本.可以接受这样的输入的东西:

I'm trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these:

./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

我的内部代码是这样的:

My internal code looks like this:

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 只接受第一个参数,并将其视为字符串.我如何让它期望"一个整数列表?

The problem seems pretty straightforward: argh is only accepting the first argument, and treating it as a string. How do I make it "expect" a list of integers instead?

我看到 这是如何在 optparse 中完成的,但是(未弃用的)argparse 呢?或者使用 argh 更好的装饰语法?这些看起来更像pythonic.

I see how this is done in optparse, but what about the (not-deprecated) argparse? Or using argh's much nicer decorated syntax? These seem much more pythonic.

推荐答案

使用 argparse,你只需使用 type=int

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', '--arg', nargs='+', type=int)
print parser.parse_args()

示例输出:

$ python test.py -a 1 2 3
Namespace(arg=[1, 2, 3])

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

I'm not familiar with argh, but it seems to be just a wrapper around argparse and this worked for me:

import argh

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

parser = argh.ArghParser()
parser.add_commands([main])
parser.dispatch()

示例输出:

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

这篇关于python argh/argparse:如何将列表作为命令行参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-22 19:07