python 使用选项从终端获取文档字符串
python get docstring from terminal using option
假设我有一个文件
myfile.py
"""
long documentation of myfile.py
...
"""
# tons of stuf
# this include some functions and their documentation
我也愿意
bash $ python myfile.py -h
这样它显示所有文档但不执行 tons of stuff
。 (我不在乎选项是 --help
而不是 -h
。)
我很确定我已经在某个地方看到过它,但我找不到了。跟 and to this second question有关系吗?
argparse
使用argparse
,可以将__doc__
字符串传递给Argparse
的描述参数来显示
#!/usr/bin/env python
"""
long documentation of myfile.py
...
"""
# tons of stuf
# this include some functions and their documentation
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)
运行 python 文件
$ python myfile.py --help
假设我有一个文件
myfile.py
"""
long documentation of myfile.py
...
"""
# tons of stuf
# this include some functions and their documentation
我也愿意
bash $ python myfile.py -h
这样它显示所有文档但不执行 tons of stuff
。 (我不在乎选项是 --help
而不是 -h
。)
我很确定我已经在某个地方看到过它,但我找不到了。跟
argparse
使用argparse
,可以将__doc__
字符串传递给Argparse
#!/usr/bin/env python
"""
long documentation of myfile.py
...
"""
# tons of stuf
# this include some functions and their documentation
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)
运行 python 文件
$ python myfile.py --help