【发布时间】:2013-01-19 13:32:50
【问题描述】:
我想解析一个必需的位置参数,其中包含一个以逗号分隔的整数列表。如果第一个整数包含前导减号 ('-'),则 argparse 会报错:
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 作为有效参数?
【问题讨论】:
-
以防万一有人需要这个,如果 --test 接受参数,你可以这样做:
python example.py --test=-1,2,3,4
标签: python command-line-arguments argparse