gpt4 book ai didi

python - 参数解析 : ValueError when using --help or -h option with nargs

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:27 24 4
gpt4 key购买 nike

当使用 argparse 时,我得到了这个奇怪的 ValueError 帮助选项。所有其他选项都可以正常工作。只有帮助选项不起作用,这很奇怪。

这是错误信息:

chaudhary@localhost:~/code/python/logmein$ ./logmein.py --bla
Usage: ./logmein.py [filename <Default: .login.txt>] || [password] || [username password]
chaudhary@localhost:~/code/python/logmein$ ./logmein.py --boo
Usage: ./logmein.py [filename <Default: .login.txt>] || [password] || [username password]
chaudhary@localhost:~/code/python/logmein$ ./logmein.py -b
Usage: ./logmein.py [filename <Default: .login.txt>] || [password] || [username password]
chaudhary@localhost:~/code/python/logmein$ ./logmein.py -h
Unexpected Error: <class 'ValueError'>
Details: unsupported format character 'p' (0x70) at index 1
Traceback (most recent call last):
File "./logmein.py", line 222, in <module>
main(sys.argv)
File "./logmein.py", line 158, in main
args, otherthings = parser.parse_known_args()
File "/usr/lib64/python3.3/argparse.py", line 1737, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/lib64/python3.3/argparse.py", line 1943, in _parse_known_args
start_index = consume_optional(start_index)
File "/usr/lib64/python3.3/argparse.py", line 1883, in consume_optional
take_action(action, args, option_string)


File "/usr/lib64/python3.3/argparse.py", line 1811, in take_action
action(self, namespace, argument_values, option_string)
File "/usr/lib64/python3.3/argparse.py", line 1015, in __call__
parser.print_help()
File "/usr/lib64/python3.3/argparse.py", line 2339, in print_help
self._print_message(self.format_help(), file)
File "/usr/lib64/python3.3/argparse.py", line 2323, in format_help
return formatter.format_help()
File "/usr/lib64/python3.3/argparse.py", line 276, in format_help
help = self._root_section.format_help()
File "/usr/lib64/python3.3/argparse.py", line 206, in format_help
func(*args)
File "/usr/lib64/python3.3/argparse.py", line 293, in _format_usage
usage = usage % dict(prog=self._prog)
ValueError: unsupported format character 'p' (0x70) at index 1

这是我的代码

# Parse command line arguments
from argparse import ArgumentParser
usage = "%prog [-f credential_file]"
parser = ArgumentParser(usage=usage)
parser.add_argument("-f", "--file", type=str, dest="file",
help="Use the specified file")
parser.add_argument("-o", "--logout", action='store_true', dest="logout",
help="Logout")
#parser.add_argument('otherthings', nargs='*')
#args = parser.parse_args()
args, otherthings = parser.parse_known_args()
argc = len(otherthings)

if args.file != None:
username, password = parse_file_for_credential(args.file)

现在我找不到为什么会出现这个 ValueError,而且也只是针对 --help 选项。

最佳答案

问题是,当 argparse 尝试插入您的 usage 字符串时,Python 会看到以下字符序列:%p。因为 p 不是 a valid conversion flag , Python 引发了 ValueError

您可以自己在 REPL 中生成此错误:

>>> "This is valid: %s" % "magic"
"This is valid: magic"

>>> "This will raise a ValueError: %p" % "magic"
ValueError: unsupported format character 'p' (0x70)

发生这种情况的原因是因为您使用了 %prog 而不是正确的 %(prog)s (请注意 %s 中键周围的括号)。按照 Rob 的建议将 usage = "%prog [-f credential_file]" 更改为 usage = "%(prog)s [-f credential_file]" 一切都会正常进行。

为什么 argparse 使用这种格式化语法?

argparse 通过named 格式参数提供程序名称等元数据,以允许参数以任何顺序出现,并允许重复。位置参数不能重复使用,必须按照提供的顺序出现:

>>> "If I want another %s then I need to add another %s" % ("param", "placeholder")
"If I want another param then I need to add another placeholder"
# There is no way to change the order around to be
# "If I want another placeholder then I need to add another param"
# without changing the order of the parameters passed to `%`

虽然命名参数可以重复并以任何顺序使用:

>>> s = "Any order, %(two)s / %(one)s. Repeats %(one)s / %(two)s are possible"
>>> s % {"one": "first", "two": "last"}
"Any order, last / first. Repeats first / last are possible"

关于python - 参数解析 : ValueError when using --help or -h option with nargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26247719/

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