Command Line Args /w optparse

+1 Colonel Panic · June 12, 2014
Here is a simple script that will take command line options from execution. 

Often you want to pass variables and information to do something with them.  (For this example we wont do anything with the variables other than assign them to a dictionary.

We will take the scenario of an employee time punch.  We will call the script with passing it parameters of the employee, his start time, and end time.  We will also require the employee name and start time.


scochran@MillenniumFalcon:~/git/templates$ ./optparseexample.py -p "Ricky Bobby" -s 07
{'employee': 'Ricky Bobby', 'start_time': '07', 'end_time': '11'}
Ricky Bobby
07
11
<type 'instance'>
{'employee': 'Ricky Bobby', 'start_time': '07', 'end_time': '11'}


Here you see we call the script "optparseexample.py and pass it two parameters of "Ricky Bobby" and an hour of 07.   Damnit Ricky Bobby, you wake up early!!  Also note that we are putting the employee name in quotes because there is a space between the names.  Without the quote python will just dump "Bobby" and set the name to just "Ricky."

The script looks like so:


#!/usr/bin/env python


from optparse import OptionParser
import os
import os.path
import sys
import datetime
from subprocess import Popen, PIPE



def get_options():
"""
Parses commandline options
"""

usage = """Usage: %prog [options]

This script sets the start and end time for an employee."""

parser = OptionParser(usage = usage)

parser.add_option(
"-p", "--employee",
action = "store",
dest = "employee",
type = "string",
help = "employee name of the employee to consider",
)

parser.add_option(
"-s", "--start-time",
action = "store",
dest = "start_time",
type = "string",
help = "Time to start serch by 24 hour UTC",
)

parser.add_option(
"-e", "--end-time",
action = "store",
dest = "end_time",
type = "string",
help = "Time to end search. " \
"Defaults to looking all the way to current hour",
)


opts = parser.parse_args()[0]

if not opts.employee:
parser.error("Must specify a employee")

if not opts.start_time:
parser.error("Must specify a start time")

if not opts.end_time:
opts.end_time = datetime.datetime.now().strftime('%H')

return opts



if __name__ == '__main__':
opts = get_options()
print opts
print opts.employee
print opts.start_time
print opts.end_time
print type(opts)
options = {'employee': opts.employee, 'start_time': opts.start_time, 'end_time': opts.end_time}
print options


In the main we call on get_options() and assigns the values to an opts object.  Notice that when we print type(opts) it shows that it is of datatype Instance.  There are many things that can be done with the opts object but this is beyond the scope of this lesson.  

Post a Reply

Replies

Oldest  Newest  Rating
0 Yoncho Yonchev · August 20, 2014
I am using SublimeREPL plugin and IPython works out of the box. It is like extended console for Python.
0 Source Slayer · June 12, 2014
Don't use optparse, the argparse library is better and it has Python 3 support.
  • 1

Python

107,304 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator