Tsathoggua
Tsathoggua

Reputation: 819

python get docstring from terminal using option

Let us say I have a file

myfile.py

"""
long documentation of myfile.py
...
"""

# tons of stuf
# this include some functions and their documentation

and I would like to do

bash $ python myfile.py -h

such that it displays all the documentation but does not execute the tons of stuff. (I don't care if the option is --help instead of -h.)

I am pretty sure I have already seen it somewhere but I can't find it. Is it related to this question and to this second question?

Upvotes: 0

Views: 1430

Answers (1)

Surajano
Surajano

Reputation: 2688

argparse

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

Run the python file

$ python myfile.py --help

Upvotes: 4

Related Questions