Why is the argparse module so inflexible?

Robert Kern robert.kern at gmail.com
Thu Jun 27 15:47:43 EDT 2013


On 2013-06-27 17:02, Dave Angel wrote:
> On 06/27/2013 09:49 AM, Andrew Berg wrote:
>> On 2013.06.27 08:08, Roy Smith wrote:
>>> Can you give us a concrete example of what you're trying to do?
>> The actual code I've written so far isn't easily condensed into a short simple
>> snippet.
>> I'm trying to use argparse to handle all the little details of parsing and
>> verifying arguments in the precmd hook for a cmd.Cmd child class.
>> argparse's help system is more sophisticated than cmd's help and does all the
>> work of verifying arguments.
>> The problem I keep running into is that I can't handle any bad input very
>> well. I would have to override every method that catches
>> ArgumentError in order to get a useful exception that I would then handle.
>> If I input something that begins with '-' that isn't recognized, parse_args
>> doesn't even raise the exception; it just quits.
>
> No, it raises the SystemExit exception.  if you don't catch it, then the program
> exits.  Perhaps it's not clear to you, but sys.exit() just raises the SystemExit
> exception, as  Joshua pointed out.

Internally, the parser raises ArgumentError which has some useful pieces of 
information, specifically, the name of the argument that failed to parse. 
Unfortunately, it catches that error in parse_known_args(), then formats that 
information into a message string to pass to the error() method, which by 
default raises SystemExit with just that message string. It is somewhat 
difficult to override the parse_known_args() to not lose that information from 
the ArgumentError because you will have to copy-paste the rest of the code in there.

So yes, you can override the error() method or catch SystemExit if all you want 
is the formatted message string, but I have to agree that there is a missed 
opportunity to make argparse more widely usable for other command-line like 
parsing tasks[1].

[1] As an existence proof, I offer you one that I wrote for handling IPython's 
%magic commands. I just needed the formatted string, so I could just get away 
with overriding error().

https://github.com/ipython/ipython/blob/master/IPython/core/magic_arguments.py

-- 
Robert Kern

"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 mailing list