现在我正在使用这个:
parser = argparse.ArgumentParser(description='Run the Foo',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
这样打印出默认值:
--install-only Do not run benchmark or verification, just install and
exit (default: False)
有没有一种简单的方法可以同时打印出类型,如下所示:
--install-only Do not run benchmark or verification, just install and
exit (default: False) (type: Boolean)
最佳答案
您可以创建自己的 HelpFormatter
类,灵感来自 argparse.py
中包含的类:
class DefaultsAndTypesHelpFormatter(argparse.HelpFormatter):
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not argparse.SUPPRESS:
defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
if action.type:
help += ' (type: %(type)s)'
return help
这将主要执行您想要的操作,但请注意它不会打印 action='store_true'
的类型。我认为这没关系,因为 (default: False)
已经很清楚了,但如果你想更明确,你可以添加一个子句,比如 if isinstance(action, argparse._StoreTrueAction)
并添加任何你喜欢的内容。
关于python - argparse:包括默认值并键入 '--help',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479254/