如何使用argparse解析带前导减号(负数)的位置参数 [英] How to parse positional arguments with leading minus sign (negative numbers) using argparse

查看:159
本文介绍了如何使用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.

这篇关于如何使用argparse解析带前导减号(负数)的位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆