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

查看:15
本文介绍了如何使用 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天全站免登陆