gpt4 book ai didi

python - 使用 optparse 或 argparse 处理使用相同选项的多个参数

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:33 26 4
gpt4 key购买 nike

我正在尝试编写一个 python 脚本,它可以在运行脚本时回显用户键入的任何内容

现在,我的代码是(version_msg 和 usage_msg 现在不重要)

from optparse import OptionParser 

version_msg = ""
usage_msg = ""
parser = OptionParser(version=version_msg, usage=usage_msg)
parser.add_option("-e", "--echo", action="append", dest="input_lines", default=[])

但如果我尝试运行脚本 (python options.py -e hello world),它只会回显 ['hello']。我该如何解决这个问题,让它输出 ['hello', 'world']?

最佳答案

argparse 中这很简单,使用它的 nargs 参数:

In [245]: parser = argparse.ArgumentParser()
In [246]: parser.add_argument('-e','--echo', nargs='+');
In [247]: parser.parse_args(['-e','hello','world'])
Out[247]: Namespace(echo=['hello', 'world'])

nargs 用于指定 Action 需要多少个字符串。 '+'表示一个或多个。结果收集在一个列表中。它根据正则表达式的用法对 nargs 值进行建模(例如,'?' 和 '*' 也有效)。

In [248]: parser.print_help()
usage: ipython3 [-h] [-e ECHO [ECHO ...]]

optional arguments:
-h, --help show this help message and exit
-e ECHO [ECHO ...], --echo ECHO [ECHO ...]

查看 optparse 文档,我看到一个 nargs 参数,但它必须是一个数字。对于可变数字,我们必须使用 callback 中所述:

https://docs.python.org/2/library/optparse.html#callback-example-6-variable-arguments

使用本节定义的函数:

In [266]: parser = optparse.OptionParser()
In [267]: parser.add_option('-e','--echo', dest='echo', action='callback', callback=vararg_callback);

In [268]: parser.parse_args(['-e','hello','world'])
Out[268]: (<Values at 0x7f0ff208a5c0: {'echo': ['hello', 'world']}>, [])

argparse中,nargs='+'收集值直到下一个---,但该分配是自上而下完成的,由主要解析例程完成,而不是为 option 本身定义的回调。

关于python - 使用 optparse 或 argparse 处理使用相同选项的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com