How can I print a Python file's docstring when executing it?

后端 未结 4 952
南笙
南笙 2020-12-29 01:49

I have a Python script with a docstring. When the parsing of the command-line arguments does not succeed, I want to print the docstring for the user\'s information.

4条回答
  •  执笔经年
    2020-12-29 02:22

    Here is an alternative that does not hardcode the script's filename, but instead uses sys.argv[0] to print it. Using %(scriptName)s instead of %s improves readability of the code.

    #!/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)
    

提交回复
热议问题