optparse question, passing unknown flags to subprocess
robert.kern at gmail.com
Thu May 21 00:31:47 CEST 2009
On 2009-05-20 16:50, Joseph Garvin wrote:
> I'm working on a python script that takes several command line flags,
> currently parsed by hand. I'd like to change the script to parse them
> with OptionParser from the optparse module. However, currently the
> script invokes a subprocess, and any flags the script doesn't
> understand it assumes are meant to be passed to the subprocess. But if
> I switch to using OptionParser, any options I haven't added to my
> parser will cause an error, instead of it ignoring those and letting
> me pass them onto the subprocess.
> What's the best/most-pythonic way to handle this? I could subclass
> OptionParser and override its exit() and error() methods as suggested
> by the docs (http://www.python.org/doc/2.4/lib/optparse-how-optik-handles-errors.html)
> and have them do nothing, but there are some errors I probably don't
> want to ignore (like if the user tries to pass a string to a known
> flag that takes an int).
Does the user specify the subprocess's executable on the command line? E.g. I
have a script called kernprof.py to run a Python script under the profiler:
$ kernprof.py [--options-for-kernprof] ./some_script.py [--options-for-script]
parser.allow_interspersed_args = False
These means that once optparse hits any argument ("./some_script.py" in this
case; basically, anything that is not an option), it will stop parsing options
and just include everything else in the args list for you to do with as you please.
However, if you are wrapping a fixed executable and you want to allow the
options to be all mixed up, I don't have a simple answer for you. You could use
"--" when you run your script to separate the script's options from the
arguments, but remembering to do that all of the time can be a pain.
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list