[英]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.