How to run a python script with options

nahanarts picture nahanarts · Feb 25, 2013 · Viewed 8.6k times · Source

I'm looking for an efficient way to write a python script that can be called using the hyphen-single-letter-space-parameter convention (e.g. python script.py -f /filename -t type -n 27, where f, t, and n are the single letters corresponding to option types and /filename, type, and 27 are their values). I am aware of the sys library and its sys.argv function as a means of grabbing the space-delimited strings following the call (see call program with arguments), but is there a sophisticated way to process these strings when they follow the convention mentioned above?

Answer

Joel Cornett picture Joel Cornett · Feb 25, 2013

You want the argparse module in the python standard library.

The argparse module contains an ArgumentParser class which you can use to parse the arguments provided by sys.argv

Usage example:

import argparse
import sys

parser = argparse.ArgumentParser(description="Does some awesome things.")
parser.add_argument('message', type=str, help="pass a message into the script")

if __name__ == '__main__':
    args = parser.parse_args(sys.argv[1:])
    print args.message

For more details, such as how to incorporate optional, default, and multiple arguments, see the documentation.