[Tutor] optional sys.argv parsing

Andre Walker-Loud walksloud at gmail.com
Thu Oct 29 22:30:53 CET 2009

Hi All,

I have a simple question.  I am writing a little program that will  
make some plots of data files.  I want to have optional args to pass,  
for example to specify the plot ranges.  I have never written a script/ 
code that takes optional args (but I have used plenty) - so I am  
feeling a little sluggish writing a good sys.argv reader.  I have the  
following few lines I made, but I am wondering if any of you have  
suggestions for how to make this better (ie more slick, more readable,  
more general etc)



import sys

if len(sys.argv) < 2:
     print('no data file specified')
elif len(sys.argv) > 2:
     if sys.argv.count('-x') > 1:
         print('error: multiple instances of "-x xmin xmax"')
     elif sys.argv.count('-x') == 1:
         xrange = sys.argv.index('-x')
     if sys.argv.count('-y') > 1:
         print('error: multiple instances of "-y ymin ymax"')
     elif sys.argv.count('-y') == 1:
         yrange = sys.argv.index('-y')
     xrange = 0
     yrange = 0

if xrange != 0:
     xmin = float(sys.argv[xrange+1])
     xmax = float(sys.argv[xrange+2])
     xmin = "x-min determined from data file"
     xmax = "x-max determined from data file"

if yrange != 0:
     ymin = float(sys.argv[yrange+1])
     ymax = float(sys.argv[yrange+2])
     ymin = "y-min determined from data file"
     ymax = "y-max determined from data file"

More information about the Tutor mailing list