[英]How can I print a Python file's docstring when executing it?
我有一个带有文档字符串的 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__)
import sys; print(sys.__doc__)
。 函数和类的文档字符串也在它们的__doc__
属性中。
这是一个不硬编码脚本文件名的替代方法,而是使用 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)
参数解析应始终使用argparse
完成。
您可以通过将__doc__
字符串传递给 Argparse 的description
参数来显示它:
#!/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
当--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 的答案的增强,因此它打印受Python argparse启发的多行文档字符串:如何在帮助文本中插入换行符? .
参数解析应始终使用 argparse 完成。
您可以通过将其传递给 Argparse 的 description 参数来显示文档字符串:
#!/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)
如果你调用这个 mysuperscript.py 并执行它,你会得到:
$ ./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
,输出将不会在文档字符串中包含换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.