How can I process command line arguments in Python? [duplicate]

As others answered, optparse is the best option, but if you just want quick code try something like this:

import sys, re

first_re = re.compile(r'^\d{3}$')

if len(sys.argv) > 1:

    if first_re.match(sys.argv[1]):
        print "Primary argument is : ", sys.argv[1]
    else:
        raise ValueError("First argument should be ...")

    args = sys.argv[2:]

else:

    args = ()

# ... anywhere in code ...

if 'debug' in args:
    print 'debug flag'

if 'xls' in args:
    print 'xls flag'

EDIT: Here’s an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.

The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put ‘-‘ or ‘–‘ in front of the optional arguments and you need to allow all the arguments to be in any order.

So here’s an example using optparse:

import sys, re, optparse

first_re = re.compile(r'^\d{3}$')

parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest="debug")
parser.add_option('--xls', action='store_true', dest="xls")
(options, args) = parser.parse_args()

if len(args) == 1:
    if first_re.match(args[0]):
        print "Primary argument is : ", args[0]
    else:
        raise ValueError("First argument should be ...")
elif len(args) > 1:
    raise ValueError("Too many command line arguments")

if options.debug:
    print 'debug flag'

if options.xls:
    print 'xls flag'

The differences here with optparse and your spec is that now you can have command lines like:

python script.py --debug --xls 001

and you can easily add new options by calling parser.add_option()

Leave a Comment