Last active
December 25, 2015 10:08
-
-
Save dbuscombe-usgs/6959051 to your computer and use it in GitHub Desktop.
example of how i like to pass arguments to python programs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment