使用 Python 的 argparse 的可选位置参数 [英] Optional positional arguments with Python's argparse

查看:32
本文介绍了使用 Python 的 argparse 的可选位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试解析可选的位置参数时遇到了以下问题:

Trying to parse optional positional arguments I ran into following issue:

示例:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('infile')
parser.add_argument('outfile', nargs='?')
parser.add_argument('-v', action='store_true')

print(parser.parse_args())

输出:

$ ./x.py -v in out
Namespace(infile='in', outfile='out', v=True)

$ ./x.py in out -v
Namespace(infile='in', outfile='out', v=True)

$ ./x.py in -v out
usage: x.py [-h] [-v] infile [outfile]
x.py: error: unrecognized arguments: out

为什么不接受第三个程序调用?这是argparse的限制吗?

Why is the third program invocation not accepted? Is this a restriction of argparse?

推荐答案

这是 argparse 的一个限制——但在 3.7 中部分解除.

This is a limitation of argparse—but one that's partially lifted in 3.7.

Unix 工具通常不声称支持选项和参数的混合,即使它们经常这样做.问题是将它与其他一些功能(如子命令)结合会导致歧义.因此,通常情况下,支持任何这些功能的库都会解决这个问题,并且不允许混合使用.或者,他们会做一些奇怪的事情——在结尾、开头和某些难以预测的情况下允许选项,但在中间不允许其他选项.

Unix tools generally don't claim to support intermixing of options and arguments, even though they often do. The problem is that combining it with some other features, like subcommands, leads to ambiguity. So, typically, libraries that support any of those features punt on the problem and don't allow intermixing. Or they do something kind of hacky—allowing options at the end, at the start, and in certain hard-to-predict cases but not others in the middle.

这就是 argparse 最初所做的.但是 3.7 添加了混合解析.

That's what argparse originally did. But 3.7 adds Intermixed parsing.

您必须手动调用 parse_intermixed_args 而不是 parse_args.

You have to manually call parse_intermixed_args instead of parse_args.

如果您尝试将它与任何不适合的功能一起使用,您将得到一个例外(即使您传递的特定参数集没有歧义 - 这应该更容易调试).

And if you try to use this with any of the features it doesn't go well with, you'll get an exception (even if there's no ambiguity for the particular set of args you pass—which should make it easier to debug).

否则,它将按预期工作:选项(当然还有它们的值)可以在命令行中的任何位置自由地与位置参数混合.

But otherwise, it'll work as expected: options (together with their values, of course) can be freely mixed with positional arguments anywhere in the command line.

不幸的是,我不知道 PyPI 上的插入式向后移植以在早期版本中获得 3.7 argparse;半官方的 argparse backport 主要针对 2.7/3.2 之前的版本根本没有它,并且只向后移植 3.4 版本.

Unfortunately, I don't know of a drop-in backport on PyPI to get 3.7 argparse in earlier versions; the semi-official argparse backport is mainly for pre-2.7/3.2 versions that don't have it at all, and only backports the 3.4 version.

这篇关于使用 Python 的 argparse 的可选位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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