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

后端 未结 4 953
南笙
南笙 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:31

    Argument parsing should always be done with argparse.

    You can display the __doc__ string by passing it to the description parameter of 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)
    

    If you call this mysuperscript.py and execute it you get:

    $ ./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
    

提交回复
热议问题