How to show the user the required arguments in a Python script?

1.5k Views Asked by At

I have a Python script that I run from the command line. The script, which uses sys.argv, requires the following six (6) arguments:

argument 1:  the script name (e.g. 'TimeSeries.py')
argument 2:  a configuration file (e.g. 'Customer1.cfg')
argument 3:  whether the resulting data is daily granular or hourly granular (e.g. -d or -h)
argument 4:  which data to retrieve (e.g. -all or -limited)
argument 5:  the number of days in the time series (e.g. '30')
argument 6:  the 'as of' date

I run this script multiple times per day and have therefore memorized the sequence of arguments.

But, there are others who might run the script infrequently and not know the required arguments (and/or the sequence).

Is there a way for them to query the argument list (along with an example of each argument)? Perhaps the doc string?

Thanks!

1

There are 1 best solutions below

0
On

There's multiple options:

  • Use the Click python library and reformat the script using this. This automatically creates a
    --help function that you can use. I have not personally used this one.

  • Use argparse from the standard library. For example:

import argparse


def get_parser():
    parser = argparse.ArgumentParser(description='Description of your script')
    parser.add_argument('name', help='The script name (e.g. "TimeSeries.py")',
                        metavar="NAME", type=str)
    # other arguments here ...
    return parser

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()

This will generate an -h option to use with help text per argument. Can be combined with my last suggestion:

  • Add a docstring to the top of the file with an explanation. Whenever no argument is given, print out the __doc__. Example with argparse again:
"""
argument 1:  the script name (e.g. 'TimeSeries.py')
argument 2:  a configuration file (e.g. 'Customer1.cfg')
argument 3:  whether the resulting data is daily granular or hourly granular (e.g. -d or -h)
argument 4:  which data to retrieve (e.g. -all or -limited)
argument 5:  the number of days in the time series (e.g. '30')
argument 6:  the 'as of' date
"""
import argparse

... # rest of script

def get_parser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('name', help='The script name (e.g. "TimeSeries.py")',
                        metavar="NAME", type=str)
    # other arguments here ...
    return parser

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()

Now calling the script with the -h option, will print out the docstring at the top, with the rest of the argument help texts. This can ofcourse also be implemented in a simple if:

if not args:  # somewhere in your own code
    print(__doc__)
    # exit code(?)