将 argparse 用于没有前缀的强制参数 [英] Using argparse for mandatory argument without prefix

查看:23
本文介绍了将 argparse 用于没有前缀的强制参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Python 应用程序中使用 argparse 模块.我的应用程序应该使用没有任何前缀的单个强制参数运行.我想不出办法来做到这一点.

I'm trying to use argparse module within my python application. My application should be run with single mandatory argument without any prefixes. I could not come up with a way to do it.

推荐答案

这是一个使用 argparse 来要求一个整数参数的简单示例:

Here is a simple example using argparse to require exactly one integer argument:

import argparse

parser = argparse.ArgumentParser(description='process an integer')
parser.add_argument('integer', metavar='N', type=int, nargs=1,
               help='an integer')
args = parser.parse_args()
print(args.integer)

将此代码保存在 argparse1.py 中并运行它会得到:

Saving this code in argparse1.py and running it gives:

$ python argparse1.py 5
[5]  

$ python argparse1.py
usage: argparse1.py [-h] N
argpars1.py: error: the following arguments are required: N

$ python argparse1.py 5 7
usage: argparse1.py [-h] N
argparse1.py: error: unrecognized arguments: 7

$ python argparse1.py test
usage: argparse1.py N
argparse1.py: error: argument N: invalid int value: 'test'

$ python argparse1.py -h
usage: argparse1.py [-h] N

process an integer

positional arguments:
  N           an integer

optional arguments:
  -h, --help  show this help message and exit

要删除可选参数,请使用 add_help=False 定义 ArgumentParser,如下所示:

To remove the optional arguments define ArgumentParser with add_help=False as follows:

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('integer', metavar='N', type=int, nargs=1)
args = parser.parse_args()
print(args.integer)

将此代码放入 argparse2.py 并对其进行测试:

Putting this code in argparse2.py and testing it gives:

$ python argparse2.py
usage: argparse2.py N
argparse2.py: error: the following arguments are required: N

$ python argparse2.py 5
[5]

$ python argparse2.py 5 7
usage: argparse2.py N
argparse2.py: error: unrecognized arguments: 7

$ python argparse2.py hello
usage: argparse2.py N
argparse2.py: error: argument N: invalid int value: 'hello'

$ python argparse2.py -h
usage: argparse2.py N
argparse2.py: error: the following arguments are required: N

可以通过导入 argparse.SUPPRESS 并使用usage=SUPPRESS 配置 ArgumentParser 来抑制所有使用消息,如下所示:

All usage messages can be suppressed by importing argparse.SUPPRESS and configuring ArgumentParser with usage=SUPPRESS as follows:

from argparse import ArgumentParser,SUPPRESS

parser = ArgumentParser(add_help=False, usage=SUPPRESS)
parser.add_argument('integer', metavar='N', type=int, nargs=1)
args = parser.parse_args()
print(args.integer)

将此代码保存在 argparse3.py 中并运行它会得到:

Saving this code in argparse3.py and running it gives:

$ python argparse3.py 5
[5]

$ python argparse3.py 5 7 9
argparse3.py: error: unrecognized arguments: 7 9

$ python argparse3.py -h
argparse3.py: error: the following arguments are required: N

无法识别的参数"错误在 ArgumentParser.parse_args() (https://hg.python.org/cpython/file/3.4/Lib/argparse.py#l1727)和需要以下参数"错误是单独硬编码的(https://hg.python.org/cpython/file/3.4/Lib/argparse.py#l1994) 两者都不需要从 API 中进行修改.后者似乎在 _parse_known_args(self, arg_strings, namespace) 中,我认为它可以被覆盖,但将涉及复制大约 250 行代码以修改 1 行以更改该错误消息.

The "unrecognized arguments" error is hardcoded in ArgumentParser.parse_args() (https://hg.python.org/cpython/file/3.4/Lib/argparse.py#l1727) and the "following arguments are required" error is separately hardcoded (https://hg.python.org/cpython/file/3.4/Lib/argparse.py#l1994) both without recourse to modification from the API. The latter appears to be in _parse_known_args(self, arg_strings, namespace) that I suppose could be overridden but would involve copying about 250 lines of code in order to modify 1 line to change that error message.

但是,可以通过只添加一个 nargs='*' 且没有类型的参数来避免这些错误消息,这有效地允许所有命令行,然后添加自定义错误处理参数,包括您自己的错误和使用消息.例如:

However, it is possible to avoid these error messages by adding just one argument with nargs='*' and no type, which effectively allows all command lines, and then adding custom error handling of arguments including your own error and usage messages. For example:

import os
import sys
from argparse import ArgumentParser,SUPPRESS

script =  os.path.basename(sys.argv[0])
usage = 'usage: ' + script + ' n (int)'

parser = ArgumentParser(add_help=False, usage=SUPPRESS)
parser.add_argument('integer', nargs='*')
args = parser.parse_args()

if (len(args.integer) == 0):
    print('error: no argument provided\n', usage, file=sys.stderr, sep = '')
    sys.exit(1)


if (len(args.integer) > 1):
    print('error: too many arguments\n', usage, file=sys.stderr, sep = '')
    sys.exit(1)

v = args.integer[0]

try:
    v = int(v)
except ValueError:
    print("error: '", v, "'", ' is not an integer\n', usage, file=sys.stderr, sep='')
    sys.exit(1)

print(v + 2)

将此代码放入 argparse4.py 并对其进行测试:

Putting this code in argparse4.py and testing it gives:

$ python argparse4.py 5
7

$ python argparse4.py
error: no argument provided
usage: argparse4.py n (int)

$ python argparse4.py 5 9
error: too many arguments
usage: argparse4.py n (int)

$ python argparse4.py hello
error: 'hello' is not an integer
usage: argparse4.py n (int)

这篇关于将 argparse 用于没有前缀的强制参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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