我刚开始使用argparse模块。我编写了下面的简化代码片段来演示我遇到的问题。
from argparse import ArgumentParser
if __name__ == '__main__':
parser = ArgumentParser('Test argparse. This string needs to be relatively long to trigger the issue.')
parser.add_argument('-f', '--fin', help='a', required = True)
parser.add_argument('-o', '--out ', help='b', required = True)
parser.add_argument('-t', '--trans', help='c', required = True)
args = parser.parse_args()
print(repr(vars(args)))
当使用-h参数运行脚本时,将会产生
AssertionError
。Traceback (most recent call last):
File "arg.py", line 10, in <module>
args = parser.parse_args()
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1707, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1739, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1945, in _parse_known_args
start_index = consume_optional(start_index)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1885, in consume_optional
take_action(action, args, option_string)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1813, in take_action
action(self, namespace, argument_values, option_string)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 1017, in __call__
parser.print_help()
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 2341, in print_help
self._print_message(self.format_help(), file)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 2325, in format_help
return formatter.format_help()
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 278, in format_help
help = self._root_section.format_help()
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 208, in format_help
func(*args)
File "C:\Users\user\AppData\Local\Continuum\Anaconda\envs\py3k\lib\argparse.py", line 329, in _format_usage
assert ' '.join(opt_parts) == opt_usage
AssertionError
缩短传递给ArgumentParser的描述字符串长度可以使其正常工作。
Python 3.3.5 |Anaconda 1.9.2 (64-bit)| (default, Mar 10 2014, 11:25:04) [MSC v.1600 64 bit (AMD64)] on win32
ArgumentParser.__init__
实际上并不接受位置参数。鉴于定义关键字参数的顺序,您正在传递一个非常长的字符串来初始化prog
属性,该属性旨在存储程序名称,就像它出现在帮助消息中一样。您试图使用该字符串初始化哪个属性? - chepnerparser = ArgumentParser(description='测试argparse。这个字符串需要相对较长才能触发问题。')
- khaglerdescription
。 - ohcamelArgumentParser(description="这里是长字符串")
。 - chepner