[Tutor] optional sys.argv parsing

Sander Sweers sander.sweers at gmail.com
Thu Oct 29 23:31:16 CET 2009


On Thu, 2009-10-29 at 17:30 -0400, Andre Walker-Loud wrote:
> 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)

You are a perfect candidate for the optparse module [1] which will do
the heavy lifting for you.

Example code relating to your code below.

------
>>> from optparse import OptionParser
>>> parser = OptionParser()
>>> parser.add_option('-f', '--file', action='store', type='string',
dest='filename', help='Explain your filename')
<Option at 0x20cf7e8: -f/--file>
>>> parser.add_option('-x', action='store', type='int', dest='x',
help='Explain your x value')
<Option at 0x20cf998: -x>
>>> parser.print_help()
Usage:  [options]

Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
                        Explain your filename
  -x X                  Explain your x value
>>>
>>> args = ['-f','somefilename','-x', '25']
>>> opts, args = parser.parse_args(args)
>>> opts.x
25
>>> opts.filename
'somefilename'
>>> type(opts.x)
<type 'int'>
-----

Greets
Sander

[1] http://docs.python.org/library/optparse.html


> import sys
> 
> if len(sys.argv) < 2:
>      print('no data file specified')
>      sys.exit(-1)
> elif len(sys.argv) > 2:
>      if sys.argv.count('-x') > 1:
>          print('error: multiple instances of "-x xmin xmax"')
>          sys.exit(-1)
>      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"')
>          sys.exit(-1)
>      elif sys.argv.count('-y') == 1:
>          yrange = sys.argv.index('-y')
> else:
>      xrange = 0
>      yrange = 0
> 
> if xrange != 0:
>      xmin = float(sys.argv[xrange+1])
>      xmax = float(sys.argv[xrange+2])
> else:
>      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])
> else:
>      ymin = "y-min determined from data file"
>      ymax = "y-max determined from data file"




More information about the Tutor mailing list