[Python-Dev] anyone tried to use optparse with something else than sys.argv?
Guido van Rossum
guido@python.org
Tue, 10 Dec 2002 10:31:06 -0500
> snuck a peek at the newly included optparse module yesterday and it seems
> option parsing will be a breeze in the future. good work!
>
> however, imho, it seems a bit too focused on initial sys.argv parsing.
> for anything else, you basically have to subclass OptionParser etc to do
> anything useful.
>
> for example, you can supply your own argument list to the parse_args()
> method, but the autohelp/version/error reporters still use sys.argv[0] as
> command name (probably not what you want). the way optparse gets the
> command name (a global function) indicates that you're not supposed to
> override it?
>
> also, even if you tell OptionParser to use your user defined Option class
> (as explained in the docs: op = OptionParser(option_class=MyOption)), it
> still adds standard Option instances to handle autohelp/version.
>
> per default, the autohelp/version/error handlers call sys.exit(). the
> docs says that if you want to change this behaviour, simply subclass
> OptionParser and/or Option and override/extend the corresponding methods.
> ofcourse, this has no effect, since standard instances are used.
>
> also, supressing the actual printing of autohelp/version/error requires
> subclassing OptionParser and Option (or sys.stdout = StringIO fiddling).
>
> so? some minor glitches and (imho) annoyances, whats the deal?
>
> well, to me, it's pretty obvious that the design effort on optparse has
> pretty much been focused strictly on initial sys.argv parsing and while
> it's extendable, other use cases (embedded consoles etc) seem to have been
> given little or no real thought.
>
> the things i mention is probably easy to fix:
>
> * make parse_args() take the whole "sys.argv" list and use the first
> element as the command name. breaks backward compatibility, i know.
> why was sys.argv[1:] used in the first place? the getopt legacy?
>
> * add parse_args_ex() that raises an exception containing the help/error
> message instead of SystemExit (SystemExit containing something means
> something went wrong, don't it?)
>
> * (simple bug) dynamically populate the OptionParser using the
> option_class and not some pre-made Option.
>
> * (simple bug) replace all %prog in help texts etc, not just the first
> occurance.
You make some good points.
A patch uploaded to SF would be welcome.
--Guido van Rossum (home page: http://www.python.org/~guido/)