argparse:将--help或-h选项与nargs一起使用时出现ValueError

问题描述 投票:1回答:2

使用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选项。

python python-3.x argparse
2个回答
3
投票

[问题是当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"

3
投票

引用the documentation

请注意,程序名称,无论是从sys.argv[0]还是从prog=参数确定,都可用于使用%(prog)s格式说明符的帮助消息。

尝试usage = "%(prog)s [-f credential_file]"

© www.soinside.com 2019 - 2024. All rights reserved.