How can I print a docstring file of a Python file when it executes?

I have a Python script with docstring. When parsing the command line arguments fails, I want to print a docstring for user information.

Is there any way to do this?

Minimal example

#!/usr/bin/env python """ Usage: script.py This describes the script. """ import sys if len(sys.argv) < 2: print("<here comes the docstring>") 
+47
python docstring
Oct 17 '11 at 9:09
source share
4 answers

Docstring is stored in the __doc__ global module.

 print(__doc__) 

By the way, this applies to any module: import sys; print(sys.__doc__) import sys; print(sys.__doc__) . Docs of functions and classes are also in the __doc__ attribute.

+57
Oct 17 '11 at 9:10
source share

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

 #!/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) 
+10
Feb 25 '13 at 9:50
source share

Argument analysis should always be done with argparse .

You can display the string __doc__ 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 
+3
Jul 28 '14 at 16:51
source share

I had such a problem, I went over the Internet and, fortunately, found the answer, recognized the sys module and created a script in Python , here it is

 if __name__=='__main__': if len(sys.argv)==2 and sys.argv[1]=='--help': print(__doc__) 

by typing ./yourscriptname.py --help or python3 yourscriptname.py --help it will show your docstring

0
Nov 26 '17 at 11:08
source share



All Articles