2017-01-09 70 views
1

我有一个名为program.py的程序,我使用argparse来执行参数解析。Python argparse - 不同的选项集

我有两个模式,我要运行这个二进制搭配: 1)模拟,它不需要参数 2)非模拟,这需要很多争论

我希望程序要么接受

python program --simulation 

python program arg1 arg2 arg3 arg4 

如果要求所有的 'ARGS' 的。

我想这样做的唯一方法是添加'required = False'到所有字段并手动检查逻辑,但我想知道是否有更优雅的方式。

下面的代码的削减版本,我有

def get_args(): 
    parser = argparse.ArgumentParser(description = "program") 
    parser.add_argument("arg1", type = bool) 
    parser.add_argument("arg2" ,type = str) 
    parser.add_argument("arg3", type = int) 
    parser.add_argument("arg4", type = str) 
    parser.add_argument("--simulation") 
    args = parser.parse_args() 
    return args 
+0

你使用'type = bool'是有问题的。请参阅我答案中的链接。 – hpaulj

回答

1

​​不能是聪明的。然而,在你的简单的情况下,可以“帮助”它来选择正确选项解析:

def get_args(args=sys.argv[1:]): 
    parser = argparse.ArgumentParser(description = "program") 
    if args and args[0].startswith("--"): 
     parser.add_argument("--simulation") 
    else: 
     parser.add_argument("arg1", type = bool) 
     parser.add_argument("arg2" ,type = str) 
     parser.add_argument("arg3", type = int) 
     parser.add_argument("arg4", type = str) 
    args = parser.parse_args(args=args) 
    return args 

所以print(get_args("--simulation xx".split()))产量:

Namespace(simulation='xx') 

,因为第一个参数与--开始。任何其他选项都无法按预期方式执行命令行解析。

print(get_args("True foo 3 bar".split()))收率:

Namespace(arg1=True, arg2='foo', arg3=3, arg4='bar') 

忘记4个位置参数中的一个作为预期失败命令行解析。

顺便说一句,我已经添加了一个默认参数,如果省略读取系统参数(就像它在你的代码中那样)。否则,您可以从文本文件中读取并传递参数标记。因此,测试更容易,并且可以创建可以使用其他模块的参数调用的模块,而无需通过sys.argv进行破解。

+0

工作出色,谢谢!一个简单的问题是,是否需要向'get_args'提供'参数'?或者,这只是为了让它更一般,以防我们想从文本文件中读取参数? – triplebig

+0

确切地说,看我的编辑。传递任何参数都与以前一样:从命令行解析。 –

1

这显然是​​的一个尴尬的规范,我怀疑大多数其他POSIX风格的解析器。

扫描sys.argv并调整解析器定义是一种可能的方法。

另一种是用一个2级剖析,以parse_known_args

import argparse 
usage = 'prog [-h] [--simulation] [arg1 arg2 arg3 arg4]' 
parser1 = argparse.ArgumentParser(usage=usage) 
parser1.add_argument('--simulation', action='store_true') 
# or omit the `store_true` if it just takes one argument 
# other possible optionals 

parser2 = argparse.ArgumentParser() 
#parser2.add_argument("arg1", type = bool) # not a valid type parameter 
parser2.add_argument("arg2") 
parser2.add_argument("arg3", type = int) 
parser2.add_argument("arg4") 
# positionals are required, unless nargs=? or * 

args, extras = parser1.parse_known_args() 
if not args.simulation: 
    args = parser2.parse_args(extras, namespace=args) 
elif extras: 
    parser1.error('cannot use --simulation with args') 
print(args) 

可能的运行包括:

1526:~/mypy$ python stack41556997.py -h 
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4] 

optional arguments: 
    -h, --help show this help message and exit 
    --simulation 

1526:~/mypy$ python stack41556997.py --simulation 
Namespace(simulation=True) 

1527:~/mypy$ python stack41556997.py 1 2 3 
Namespace(arg2='1', arg3=2, arg4='3', simulation=False) 

1527:~/mypy$ python stack41556997.py 1 2 3 --sim 
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4] 
stack41556997.py: error: cannot use --simulation with args 

注意,帮助不包括两套。我在自定义用法中包含了一些信息,但arg#没有帮助行。生成一个好的help消息将与您的规格尴尬。

我跳过了你的arg1type=bool不是有效的type参数。请参阅我的解释Parsing boolean values with argparse

我将--simulation更改为store_true,因为您说它没有任何参数。这是接受True/False的正常方式。

Subparsers通常是接受不同模式参数的最佳工具。在这种情况下,你可以有一个叫做'simulate'的subparser不需要任何参数,另一个叫'somethingelse'需要4个参数。

我打算建议一个与--simulation和​​可选项互斥的组。但一个store_true的论点不适用于这样的组。

=============

子分析器路线:

parser = argparse.ArgumentParser() 
sp = parser.add_subparsers(dest='cmd') 
sp.add_parser('simulate') 
parser2 = sp.add_parser('other') 
parser2.add_argument("arg2") 
parser2.add_argument("arg3", type = int) 
parser2.add_argument("arg4") 
print(parser.parse_args()) 

测试:

1552:~/mypy$ python stack41556997.py -h 
usage: stack41556997.py [-h] {simulate,other} ... 

positional arguments: 
    {simulate,other} 

optional arguments: 
    -h, --help  show this help message and exit 
1557:~/mypy$ python stack41556997.py simulate 
Namespace(cmd='simulate') 
1557:~/mypy$ python stack41556997.py other -h 
usage: stack41556997.py other [-h] arg2 arg3 arg4 

positional arguments: 
    arg2 
    arg3 
    arg4 

optional arguments: 
    -h, --help show this help message and exit 
1557:~/mypy$ python stack41556997.py other 1 2 3 
Namespace(arg2='1', arg3=2, arg4='3', cmd='other') 

注意,arg3type转换的输入到一个整数。其他人留作字符串。有了这个设置,args.cmd将成为子分析器的名称,与布尔型args.simulation属性不完全相同。

==================

甲标记默认参数不要求的。位置参数是必需的,除非nargs值为'?'要么 '*'。您无法为位置提供“必需”参数。