Sunday, 13 October 2013

How to pass arguments to python programs ...

... the right way (in my opinion). This is the basic template I always use. Not complicated, but the general formula might be useful to someone.

It allows you to pass arguments to a program with the use of flags, so they can be provided in any order. It has a 'help' flag (-h), will raise an error if no arguments are passed.

In this example one of the inputs (-a) is supposed to be a file. If the file is not provided, it uses Tkinter to open a simple 'get file' window dialog.

It then parses the other arguments out. Here I have assumed one argument is a string, one is a float, and one is an integer. If any arguments are not provided, it creates variables based on default variables. It prints everything it's doing to the screen.


# these are the libraries needed
import sys, getopt
from Tkinter import Tk
from tkFileDialog import askopenfilename
import numpy as np
# get list of input arguments and pre-allocate arrays
argv = sys.argv[1:]
inputfile = ''; arg2 = ''
arg3 = ''; arg4 = ''
# parse inputs to variables
try:
opts, args = getopt.getopt(argv,"ha:b:c:d:")
except getopt.GetoptError:
print 'my_script.py -a <inputfile> -b <arg2> -c <arg3> -d <arg4>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h': # h is 'help'
print 'my_script.py -a <inputfile> -b <arg2> -c <arg3> -d <arg4>'
sys.exit()
elif opt in ("-a"):
inputfile = arg
elif opt in ("-b"):
arg2 = arg
elif opt in ("-c"):
arg3 = arg
elif opt in ("-d"):
arg4 = arg
# prompt user to supply file if no input file given
if not inputfile:
print 'An input file is required!!!!!!'
# we don't want a full GUI, so keep the root window from appearing
Tk().withdraw()
# show an "Open" dialog box and return the path to the selected file
inputfile = askopenfilename(filetypes=[("JPG files","*.jpg")])
# print given arguments to screen and convert data type where necessary
# let's assume arg2 is meant to be an integer, arg3 is a float, and arg4 is a string
# let's further assume arg2 and arg3 are meant to be numpy arrays
if inputfile:
print 'Input file is %s' % (inputfile)
if arg2:
arg2 = np.asarray(arg2,int)
print 'Argument 2 is %s' % (str(arg2))
if arg3:
arg3 = np.asarray(arg3,float)
print 'Argument 3 is %s' % (str(arg2))
if arg4:
print 'Argument 4 is %s' % (arg4)
# if arguments not supplied, use defaults
if not arg2:
arg2 = 100
print '[Default] Argument 2 is %s' % (str(arg2))
if not arg3:
arg3 = 0.1
print '[Default] Argument 3 is %s' % (str(arg3))
if not arg4:
arg4 = 'hello'
print '[Default] Argument 4 is %s' % (arg4)

No comments: