Re: Re: optparse questions
Jeremy Conlin <[email protected]> Mon, 7 Jun 2004 12:11:30 -0400
| Newsgroups | gmane.comp.python.optik.user |
|---|---|
| Message-ID | <[email protected]> |
Thanks all for your help. I think I understand much better how to use
the optparse module. As I find more questions while writing the
script, I know where to ask.
Thanks,
Jeremy
On Jun 6, 2004, at 12:35 PM, David Goodger wrote:
> Greg Ward wrote:
> [Jeremy Conlin (I presume)]
> >> I am creating a script that requires one argument (the input
> >> filename) and one optional argument (the output filename).
>
> [Greg Ward]
> > It sounds to me like you don't quite understand the difference
> > between arguments, options, and option arguments.
>
> While the Tao doc is useful, I don't think there's any problem with
> Jeremy's approach, syntax like this:
>
> command [options] file1 [file2]
>
> That's options (optional by default), one required positional
> argument, and one optional positional argument. We use similar syntax
> with Docutils:
>
> rst2html.py [options] [<source> [<destination>]]
>
> If one positional argument is passed, it's the source. If two, the
> first is the source and the second is the destination. The defaults
> are STDIN for source and STDOUT for destination. So "rst2html.py"
> (with no arguments) is the equivalent of "rst2html.py - -" using the
> standard meaning of "-".
>
> To code Jeremy's command (one required positional argument, one
> optional), use this:
>
> parser = OptionParser(
> usage="%prog [options] input_file [output_file]")
> parser.add_option("-m", "--meshtal", action="store_true", dest='m',
> default=False,
> help='Input deck uses mesh tallies')
> (options, args) = parser.parse_args()
> if len(args) < 1 or len(args) > 2:
> parser.error("wrong number of arguments: 1 or 2 required")
> infile = open(args[0])
> if len(args) == 2:
> outfile = open(args[1], "w")
> else:
> outfile = sys.stdout
> # check for -m option:
> if options.m:
> # do something
> ...
>
> I'd drop the "dest='m'" though, and use the default of "meshtal".
> Makes the code more self-documenting.
>
> Definitely do read the updated docs.
>
> --
> David Goodger <http://python.net/~goodger>
>
-------------------------------------------------------
This SF.Net email is sponsored by: GNOME Foundation
Hackers Unite! GUADEC: The world's #1 Open Source Desktop Event.
GNOME Users and Developers European Conference, 28-30th June in Norway
http://2004/guadec.org