如何使用argparse解析带前导减号(负数)的位置参数
我想解析一个必需的位置参数,该参数包含逗号分隔的整数列表.如果第一个整数包含前导减号('-'),则argparse会抱怨:
I would like to parse a required, positional argument containing a comma-separated list of integers. If the first integer contains a leading minus ('-') sign, argparse complains:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('positional')
parser.add_argument('-t', '--test', action='store_true')
opts = parser.parse_args()
print opts
$ python example.py --test 1,2,3,4
Namespace(positional='1,2,3,4', test=True)
$ python example.py --test -1,2,3,4
usage: example.py [-h] [-t] positional
example.py: error: too few arguments
$ python example.py --test "-1,2,3,4"
usage: example.py [-h] [-t] positional
example.py: error: too few arguments
我已经看到人们建议使用除-
之外的其他字符作为标志字符,但是我宁愿不这样做.是否有另一种方法可以配置argparse以同时允许--test
和-1,2,3,4
作为有效参数?
I've seen people suggest using some other character besides -
as the flag character, but I'd rather not do that. Is there another way to configure argparse to allow both --test
and -1,2,3,4
as valid arguments?
您需要在命令行参数中插入--
:
You need to insert a --
into your command-line arguments:
$ python example.py --test -- -1,2,3,4
Namespace(positional='-1,2,3,4', test=True)
双破折号使argparse停止寻找更多可选开关;这是处理此命令行工具用例的事实上的标准方法.
The double-dash stops argparse looking for any more optional switches; it's the defacto standard way of handling exactly this use case for command-line tools.