Nathan Fellman
Nathan Fellman

Reputation: 127428

How can I specify that some command line arguments are mandatory in Python?

I'm writing a program in Python that accepts command line arguments. I am parsing them with getopt (though my choice of getopt is no Catholic marriage. I'm more than willing to use any other library). Is there any way to specify that certain arguments must be given, or do I have to manually make sure that all the arguments were given?

Edit: I changed all instances of option to argument in response to public outcry. Let it not be said that I am not responsive to people who help me :-)

Upvotes: 8

Views: 17958

Answers (3)

huangkaiyi
huangkaiyi

Reputation: 123

From argparse library, you can use required=True in option

import argparse

parser = argparse.ArgumentParser(description="Help msg", 
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument("-i", "--intput",  help="image input",  required=True)
parser.add_argument("-o", "--output",  help="image output", required=True)
parser.add_argument("-v", "--version", help="version"                    )

and then compile

> main.py -h
Help msg
optional arguments:
-h, --help     show this help message and exit
-i, --input    image input
-o, --output   image output
-v, --version  version

> main.py
main.py: error: the following arguments are required: -i/--intput, -o/--output

and you have it, -i and -o options are mandatory.

visit this website, he explain it well.

Upvotes: 0

Mikhail Churbanov
Mikhail Churbanov

Reputation: 4500

As for me I prefer using optparse module, it is quite powerful, for exapmle it can automatically generate -h message by given options:

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()

You should manually check if all arguments were given:

if len(args) != 1:
        parser.error("incorrect number of arguments")

Making options mandatory seems to be quite strange for me - they are called options not without any sense...

Upvotes: 9

Martin v. Löwis
Martin v. Löwis

Reputation: 127447

The simplest approach would be to do it yourself. I.e.

found_f = False
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
for o, a in opts:
    if o == '-f':
      process_f()
      found_f = True
    elif ...
if not found_f:
    print "-f was not given"
    usage()
    sys.exit(2)

Upvotes: 10

Related Questions