如何使用 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.