themaster
themaster

Reputation: 473

Displaying help through command line argument

I have a python program that I am running through command line arguments. I have used sys module.

Below is my test.py Python file where I am taking all the args:

if len(sys.argv) > 1:
    files = sys.argv

get_input(files)

The get_input method is in another Python file where I have the options defined.

options = {

    '--case1': case1,
    '--case2': case2,

}


def get_input(arguments):

    for file in arguments[1:]:
        if file in options:
            options[file]()
        else:
            invalid_input(file)

To run:

python test.py --case1 --case2

My intentions are that I want to show the user all the commands in case they want to read the docs for that.

They should be able to read all the commands like they usually are in all the package for reading help, python test.py --help . With this they should be able to look into all the commands they can run.

How do I do this?

Upvotes: 1

Views: 1112

Answers (2)

Arount
Arount

Reputation: 10403

One of the best quality a Python developer can be proud of is to use built-in libraries instead of custom ones. So let's use argparse:

import argparse

# define your command line arguments
parser = argparse.ArgumentParser(description='My application description')
parser.add_argument('--case1', help='It does something', action='store_true')
parser.add_argument('--case2', help='It does something else, I guess', action='store_true')

# parse command line arguments
args = parser.parse_args()

# Accessing arguments values
print('case1 ', args.case1)
print('case2 ', args.case2)

You can now use your cmd arguments like python myscript.py --case1

This comes with a default --help argument you can now use like: python myscript.py --help which will output:

usage: myscript.py [-h] [--case1] [--case2]

My application description

optional arguments:
  -h, --help  show this help message and exit
  --case1     It does something
  --case2     It does something else, I guess

Upvotes: 3

Amit Nanaware
Amit Nanaware

Reputation: 3346

Hi you can use option parser and add your options and related help information.

It has by default help option which shows all the available options which you have added.

The detailed document is here. And below is the example.

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

Upvotes: 1

Related Questions