2

I want to create a script like this

./myscript.py -g parser -a parserapp 

and whenever the script is missing one option such as ./myscript.py -g parser, it will print out usage and exit the script

The script should be: ./myscript.py -g parser -a parserapp 

So, my question is how can I check if option -a or-g is missing; so, it can print out the usage for the script and exit.

Thank you for your help

3
  • 6
    Look at existing modules already dealing with command line options, such as argparse Commented Mar 16, 2016 at 8:45
  • Yep, argparse is the way. Don't reinvent the wheel. Commented Mar 16, 2016 at 8:46
  • I did, and there seem to be nothing that can help me to check if my option is missing. Commented Mar 16, 2016 at 8:46

4 Answers 4

3

Use argparse

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-g", "--gggg", help="g parameter",required=True)
parser.add_argument("-a", "--aaaa", help="a parameter",required=True)
args = parser.parse_args()
print args.g, args.a

When you run it with -h it will show help:

~#:python myscript.py -h
usage: myscript.py [-h] -g GGGG -a AAAA

optional arguments:
  -h, --help            show this help message and exit
  -g GGGG, --gggg GGGG  g parameter
  -a AAAA, --aaaa AAAA  a parameter

If you miss a parameter it will print error:

myscript.py: error: argument -g/--gggg is required
Sign up to request clarification or add additional context in comments.

Comments

1

Parsing of parameters can be done with optparse or argparse. You can make nifty help options and so on. It's also easy to make different kinds of parameters to be accepted.

Use argparse: https://docs.python.org/2/howto/argparse.html

Comments

1

For your need argparse can check wether an argument is missing or not like this :

 import argparse
 parser = argparse.ArgumentParser(description='My Super Script')
 parser.add_argument(
        '--parser', '-p',
        required=True,
        help='Parser Type'
        )
 parser.add_argument(
        '--application', '-a',
        required=True,
        help='Application Name'
        )
 args = parser.parse_args()

By default argparse will consider a named argument optional unless you specify required=True If the two args are not provided this will print a default help.
ref

Comments

1

You can use argparse module.
For Python3.x, you can look here.
For Python2.x, you can look here.

Apart from argparse, you can also use getopt module.
Use getopt:
https://docs.python.org/3.1/library/getopt.html(Python3.x)
https://docs.python.org/2/library/getopt.html(Python2.x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.