Python argparse,位置参数后的值 [英] Python argparse, Value after positional argument
问题描述
所以我正在编写这个非常小的程序来执行 http get 和 post 请求.请求如下:
So I'm writing this very small program to do http get and post requests. The requests are as follows:
requestApp.py help
requestApp.py help get
requestApp.py help post
requestApp.py get [-v] [-h key:value] URL
requestApp.py post [-v] [-h key:value] [-d inline-data] [-f file] URL
如您所见,-v、-h、-d、-f、URL 参数是可选的.get 和 post 参数是非可选的.我将向您展示与这种情况相关的程序片段:
As you can see, the -v, -h, -d, -f, URL arguments are optional. The get and post arguments are non-optional. I'll show you the snippet of my program that is relevant to this situation:
parser = argparse.ArgumentParser(description='httpc is a curl-like application but supports HTTP protocol only.')
parser.add_argument('command', type=str, help=help_output())
parser.add_argument('url', action='store_true', help='The URL that will be provided to perform the requested command.')
parser.add_argument('-v', '--verbose', action='store_true')
command
参数将是 help、get 或 post,而 url
参数是不言自明的.我的问题与上面的第二个和第三个命令有关,即:
The command
argument will be help, get, or post, and the url
argument is self explanatory. My question is related to the second and third commands above, namely:
requestApp.py help get
requestApp.py help post
如何确保在键入 help get
时,get
不会在 URL 中注册(help post
也是如此).另外,当我包含一个 URL 时,我希望它被存储在 URL 参数中.我是否必须手动评估通过 if 语句传递的参数?或者有更好的方法吗?
How can I make sure that when typing help get
, the get
will not be registered in the URL (same for help post
). In addition, when I do include a URL, I want it to be stored inside of the URL argument. Would I have to manually evaluate the arguments passed through if statements? Or there is a better way to do it?
推荐答案
也许最接近 argparse
解决方案的可能是:
Perhaps the closest an argparse
solution can come, at least without going the subparser route, is:
import argparse
import sys
print(sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('-k', '--keyvalue')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-d', '--data')
parser.add_argument('-f', '--file')
parser.add_argument('pos1', choices = ['help', 'get', 'post'])
parser.add_argument('pos2')
args = parser.parse_args()
print(args)
得到的帮助是:
1744:~/mypy$ python stack54383659.py get aurl -h
['stack54383659.py', 'get', 'aurl', '-h']
usage: stack54383659.py [-h] [-k KEYVALUE] [-v] [-d DATA] [-f FILE]
{help,get,post} pos2
positional arguments:
{help,get,post}
pos2
optional arguments:
-h, --help show this help message and exit
-k KEYVALUE, --keyvalue KEYVALUE
-v, --verbose
-d DATA, --data DATA
-f FILE, --file FILE
合身并不完美.例如,您可以只提供 help
,但您可以只提供 -h
.第二个位置值可以是任何字符串、'get'、有效的 url 或其他东西.您自己的代码必须对此进行验证.key:value
位需要您自己解析.
The fit isn't perfect. For example you can give just help
, but you can provide just -h
. The 2nd positional value can be any string, 'get', a valid url or something else. Your own code will have to valid that. The key:value
bit requires your own parsing.
在 argparse
解析方式中,optionals
可以以任何顺序出现.这两个位置必须以给定的顺序出现(相对于彼此).
In the argparse
way of parsing the optionals
can occur in any order. The two positionals have to occur in the given order (relative to each other).
在较新的 Python 中,我可以将最后一个位置更改为可选",并使用新的 intermixed
解析器.这将允许我只提供帮助"(或只提供获取"):
In newer Pythons I can change the last positional to be 'optional', and use the new intermixed
parser. That would allow me to give just 'help' (or just 'get'):
parser.add_argument('pos2', nargs='?')
args = parser.parse_intermixed_args()
如果两个位置值由标志分隔,则需要
intermixed
.由于一些复杂的原因,常规解析可能会消耗?"参数过早地给您留下了一个额外的无法识别的字符串.
intermixed
is needed if the two positional values are separated by flags. For some complex reasons, the regular parsing may consume the '?' argument prematurely leaving you with an extra unrecognized string.
另一种方法是定义所有标记的参数,并使用parse_known_args
.非标志值将在 extras
列表中,您可以根据需要对其进行解析.像 optparse
这样的旧解析器基本上就是这样做的.argparse
也添加了处理位置参数的有限能力,但严格按位置,而不是按值.
Another approach is to define all the flagged arguments, and use parse_known_args
. The non-flag values will be in the extras
list, which you can parse as you like. Older parsers like optparse
did essentially that. argparse
added a limited ability to handle positional arguments as well, but strictly by position, not by value.
这篇关于Python argparse,位置参数后的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!