bak*_*aky 18 python pydoc argparse
我在我的脚本中使用argparse.ArgumentParser(),我想显示我的脚本的pydoc描述作为argparse的' - help'选项的一部分.
一种可能的解决方案是使用ArgumentParser 的formatter_class或description属性来配置帮助的显示.但在这种情况下,我们需要在内部使用'pydoc'命令来获取描述.
我们还有其他方法(可能是优雅的)吗?
che*_*ner 29
您可以从__doc__全局检索脚本的docstring .要将其添加到脚本的帮助中,您可以设置description解析器的参数.
"""My python script
Script to process a file
"""
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('foo', help="Name of file to process")
p.parse_args()
Run Code Online (Sandbox Code Playgroud)
然后帮助将如下所示:
$ python tmp.py --help
usage: tmp.py [-h] foo
My python script
Script to process a file
positional arguments:
foo Name of file to process
optional arguments:
-h, --help show this help message and exit
Run Code Online (Sandbox Code Playgroud)
您可以使用epilog关键字参数而不是description将文档字符串移动到帮助的末尾,而不是紧跟使用字符串.
| 归档时间: |
|
| 查看次数: |
5769 次 |
| 最近记录: |