[Python-Dev] PEP 389: argparse - new command line parsing module

Steven Bethard steven.bethard at gmail.com
Tue Sep 29 22:57:22 CEST 2009


On Tue, Sep 29, 2009 at 1:31 PM, Paul Moore <p.f.moore at gmail.com> wrote:
> 2009/9/28 Yuvgoog Greenle <ubershmekel at gmail.com>:
>> 1. There is no chance of the script killing itself. In argparse and optparse
>> exit() is called on every parsing error (btw because of this it sucks to
>> debug parse_args in an interpreter).
>
> That one does worry me. I'd rather argparse (or any library function)
> didn't call sys.exit on my behalf - it should raise an exception. Is
> it actually true that argparse exits? (I can imagine that it might if
> --help was specified, for example. An exception may not be right here,
> but I still don't like the idea of a straight exit - I've used too
> many C libraries that think they know when I want to exit).

This is behavior that argparse inherits from optparse, but I believe
it's still what 99.9% of users want.  If you're writing a command line
interface, you don't want a stack trace when there's an error message
(which is what you'd get if argparse just raised exceptions) you want
an exit with an error code. That's what command line applications are
supposed to do.

If you're not using argparse to write command line applications, then
I don't feel bad if you have to do a tiny bit of extra work to take
care of that use case. In this particular situation, all you have to
do is subclass ArgumentParser and override exit() to do whatever you
think it should do.

>> 2. There is no chance the parser will print things I don't want it to print.
>
> That may also be bad - for example, Windows GUI-mode programs raise an
> error if they write to stdout/stderr. I could imagine using argparse
> for such a program, and wanting to do something with --help other than
> write to stdout and exit (a message box, for example). And yet, I'd
> want access to the text argparse would otherwise write to stdout.

There is only a single method in argparse that prints things,
_print_message(). So if you want it to do something else, you can
simply override it in a subclass. I can make that method public if
this is a common use case.

Steve
-- 
Where did you get that preposterous hypothesis?
Did Steve tell you that?
        --- The Hiphopopotamus


More information about the Python-Dev mailing list