Re: Re: optparse questions
David Goodger <[email protected]> Sun, 06 Jun 2004 12:35:29 -0400
| Newsgroups | gmane.comp.python.optik.user |
|---|---|
| Message-ID | <[email protected]> |
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 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