Re: optparse questions

Greg Ward <[email protected]> Sun, 6 Jun 2004 12:11:22 -0400
Newsgroups gmane.comp.python.optik.user
Message-ID <[email protected]>
[from private email; replying to the list for posterity]
> 	I am new to Python and have recently discovered the optparse 
> module and really think it is cool.  Unfortunately I am having some 
> troubles and was wondering if you could help me out.  I have read 
> through much of the documentation on the python.org website but I don't 
> quite understand how to implement optparse.  I will try to describe 
> what I am doing and what questions I have. 

First: I have recently revised the Optik (aka optparse) docs so that
they are hopefully a bit easier on first encounter.  Please go to
http://optik.sourceforge.net/, scroll down to the "Documentation"
section, and follow the "stable" links.  The basic guide in particular
changed the most.

> 	I am creating a script that requires one argument (the input 
> filename) and one optional argument (the output filename).  I don't 
> want to require the user to include the '-f' option (as you have used 
> it in the documentation) to specify a filename because that is 
> required.  I just want the script to look, determine if there are any 
> options and see how many entries there are (if two, do what is required 
> when the optional output filename is present, etc.) and then work 
> according to what it sees.  I hope that makes sense. 

It sounds to me like you don't quite understand the difference between
arguments, options, and option arguments.  Please read my rant "The Tao
of Option Parsing": http://optik.sourceforge.net/doc/stable/tao.html

Anyways, if I understand you correctly, you want something like this:

  foo [-o output_file] input_file

which I would code like this:

  parser = OptionParser(usage="%prog [-o output_file] input_file")
  parser.add_option("-o", "--output",
                    metavar="FILE",
                    help="write output to FILE (default: stdout)")
  (options, args) = parser.parse_args()
  if len(args) != 1:
      parser.error("wrong number of arguments")
  infile = open(args[0])
  if options.output is None:
      outfile = sys.stdout
  else:
      outfile = open(options.output, "w")

Well, that's enough to get you started.  Things to think about:

  * a common Unix convention is that "-" means "write to stdout" or
    "read from stdin" (depending on context) -- so if someone specifies
    "-o -" (ie.  options.output == "-"), you should write to stdout
    rather than creating a file called "-"

  * for better portability (ie. to Windows and old Mac OS), you should
    open outfile with either "t" (text) or "b" (binary) appended to
    the mode string -- see the docs on the "open" built-in for details

  * if your script is unable to open the input file or output file, it
    will bomb with an ugly traceback.  You should catch both exceptions
    and print a friendly error message, eg. using parser.error().

> 	 I want to add an option to have the script do additional 
> things if the option '-m' is present when it is called.  I added an 
> option using the following syntax: 
> 
> parser.add_option("-m", "--meshtal", action="store_true", dest='m', 
> default=False, 
>                     help='Input deck uses mesh tallies') 
> 	Once I have added one or more options, how do I determine  
> whether or not the optional output filename was included?  How can I 
> get the input filename (and output filename) from optparse?   

I think the above code answers this.  Or the recent improvements to the
basic guide might help too.

> 	I also want to have the '-h' option for help.  I thought that 
> this (and the '-f' option) was 'included' and didn't need to be 
> specified unless I wanted to overwrite it. 

Optik always includes -h/--help unless you disable it, and it
automatically includes --version if you enable it.  No other options are
automatically added by Optik, since no other options make universal
sense.

        Greg
-- 
Greg Ward <[email protected]>                         http://www.gerg.ca/
I haven't lost my mind; I know exactly where I left it.


-------------------------------------------------------
This SF.Net email is sponsored by the new InstallShield X.
From Windows to Linux, servers to mobile, InstallShield X is the one
installation-authoring solution that does it all. Learn more and
evaluate today! http://www.installshield.com/Dev2Dev/0504