Tuesday, October 23, 2012

Command Line Arguments in Python

Reading your command line arguments in Python is incredibly easy, but I have to look it up every time.  Also, there are a thousand different ways to do it as the language has evolved through the years.  This seems to be the latest (or one of the latest) ways of doing it:


#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser(description="Select a pentathalon activity")
parser.add_argument("activity", choices=["run","ride","swim","fence","shoot"])
parser.add_argument("--speed", default="slow")
args = vars(parser.parse_args())
activity = args['activity']
speed = args['speed']
print("Activity: {0}, speed: {1}".format(activity,speed))


Python handles all of the rigamarole with ensuring that your script doesn't continue if the arguments are not entered to specifications, and all the values are available for processing when it is done.  It also automatically adds a -h parameter and gives the help.

Save the above script as parsetest.py and try the following:


./parsetest.py run
./parsetest.py swim
./parsetest.py run --speed fast
./parsetest.py -h


Also: I am trying to consciously use Python3 with new things now, though this code should work in the 2.7 line as well.  The only thing I seem to have trouble with is remembering to do the print statements in the new format.  I might have to write up a summary of the print function one of these days so I can remember the pertinent stuff.

No comments:

Post a Comment