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

查看:128
本文介绍了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 反向端口主要用于没有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天全站免登陆