运行时
foo.py -h
OR
foo.py --help,
您将收到有关如何使用foo.py及其所需参数的“帮助”消息。有没有办法可以附加到这条消息?打印__doc__例如?
答案 0 :(得分:5)
当然,argparse
为您提供很多的自定义功能。 To"追加"帮助(在完成帮助消息后打印更多),例如,使用epilog
命名参数。
parser = argparse.ArgumentParser(epilog="That's all she wrote", ...)
其中...
代表"无论您希望传递给解析器构造函数"还是其他任何命名参数,相关消息将在有关参数的帮助之后打印在--help
上。
请参阅https://docs.python.org/3/library/argparse.html,了解关于argparse
的几千字(写作参考但有大量示例)和https://docs.python.org/3/howto/argparse.html#id1几千字(作为教程编写)。也许这些文档的一半是关于如何微调--help
或错误情况的消息! - )
答案 1 :(得分:2)
帮助格式化功能argparse.ArgumentParser.format_help()
如下所示:
def format_help(self):
formatter = self._get_formatter() #by default, an instance of argparse.HelpFormatter
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
所以,你可以
epilog
感兴趣)或HelpFormatter
(formatter_class
构造函数参数)以自定义这些字符串如何转换为帮助文本
argparse
模块bundles 3 alternative classes。