92

docstring を含む Python スクリプトがあります。コマンドライン引数の解析が成功しない場合、ユーザーの情報として docstring を出力したいと考えています。

これを行う方法はありますか?

最小限の例

#!/usr/bin/env python
"""
Usage: script.py

This describes the script.
"""

import sys


if len(sys.argv) < 2:
    print("<here comes the docstring>")
4

5 に答える 5

104

docstring はモジュールの__doc__グローバルに格納されます。

print(__doc__)

ちなみに、これはどのモジュールにも当てはまります: import sys; print(sys.__doc__). 関数とクラスのドキュメント文字列もその__doc__属性にあります。

于 2011-10-17T09:10:11.633 に答える
13

スクリプトのファイル名をハードコーディングせず、代わりに sys.argv[0] を使用して出力する代替方法を次に示します。%s の代わりに %(scriptName)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)
于 2013-02-25T09:50:43.963 に答える
13

引数の解析は常に で行う必要がありますargparse

Argparse__doc__のパラメーターに渡すことで、文字列を表示できます。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
于 2014-07-28T16:51:27.263 に答える