我有一个带有文档字符串的 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__
属性中。
这是一种不硬编码脚本文件名的替代方法,而是使用 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__
通过将字符串传递给description
Argparse 的参数来显示该字符串:
#!/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
这将打印__doc__
字符串when--help
是唯一的参数。
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 的描述参数来显示文档字符串:
#!/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
输出,则文档字符串中不会有换行符。