我有一个带有文档字符串的Python脚本。当命令行参数解析失败时,我想打印文档字符串以便用户了解。
是否有任何方法可以实现这一点?
最小示例
#!/usr/bin/env python
"""
Usage: script.py
This describes the script.
"""
import sys
if len(sys.argv) < 2:
print("<here comes the docstring>")
我有一个带有文档字符串的Python脚本。当命令行参数解析失败时,我想打印文档字符串以便用户了解。
是否有任何方法可以实现这一点?
#!/usr/bin/env python
"""
Usage: script.py
This describes the script.
"""
import sys
if len(sys.argv) < 2:
print("<here comes the docstring>")
文档字符串存储在模块的 __doc__
全局变量中。
print(__doc__)
顺便说一下,对于任何模块都是适用的:import sys; print(sys.__doc__)
。函数和类的文档字符串也在它们的__doc__
属性中。
help(module_name)
。 - danbgray应该总是使用argparse
进行参数解析。
您可以通过将其传递给Argparse的description
参数来显示__doc__
字符串:
#!/usr/bin/env python
"""
This describes the script.
"""
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
# Add your arguments here
parser.add_argument("-f", "--file", dest="myFilenameVariable",
required=True,
help="write report to FILE", metavar="FILE")
args = parser.parse_args()
print(args.myFilenameVariable)
如果您将此文件命名为mysuperscript.py并执行它,您会得到:
$ ./mysuperscript.py --help
usage: mysuperscript.py [-h] -f FILE
This describes the script.
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE write report to FILE
这里有一种替代方案,不是硬编码脚本文件名,而是使用sys.argv[0]打印它。使用%(scriptName)s而不是%s可以提高代码的可读性。
#!/usr/bin/env python
"""
Usage: %(scriptName)s
This describes the script.
"""
import sys
if len(sys.argv) < 2:
print __doc__ % {'scriptName' : sys.argv[0].split("/")[-1]}
sys.exit(0)
"""使用方法:{scriptName}""".format(scriptName = sys.argv[0])
。 - Cimbali--help
是唯一的参数时打印__doc__
字符串。if __name__=='__main__':
if len(sys.argv)==2 and sys.argv[1]=='--help':
print(__doc__)
适用于以下两种方式:
./yourscriptname.py --help
python3 yourscriptname.py --help
这是@MartinThoma答案的增强版,它可以打印多行docstring,灵感来自于Python argparse:如何在帮助文本中插入换行符?。
没有添加Argument parsing should always be done with argparse.
You can display the doc string by passing it to the description parameter of Argparse:
#!/usr/bin/env python """ This summarizes the script. Additional descriptive paragraph(s). """ # Edited this docstring if __name__ == '__main__': from argparse import ArgumentParser, RawTextHelpFormatter # Edited this line parser = ArgumentParser(description=__doc__ formatter_class=RawTextHelpFormatter) # Added this line # Add your arguments here parser.add_argument("-f", "--file", dest="myFilenameVariable", required=True, help="write report to FILE", metavar="FILE") args = parser.parse_args() print(args.myFilenameVariable)
If you call this mysuperscript.py and execute it you get:
$ ./mysuperscript.py --help usage: mysuperscript.py [-h] -f FILE This summarizes the script. Additional descriptive paragraph(s). optional arguments: -h, --help show this help message and exit -f FILE, --file FILE write report to FILE
formatter_class
,文档字符串中就不会有换行符。