Apart from tinkering with the argparse source, is there any way to control the exit status code should there be a problem when parse_args() is called, for example, a missing required switch?
Apart from tinkering with the argparse source, is there any way to control the
Share
I’m not aware of any mechanism to specify an exit code on a per-argument basis. You can catch the
SystemExitexception raised on.parse_args()but I’m not sure how you would then ascertain what specifically caused the error.EDIT: For anyone coming to this looking for a practical solution, the following is the situation:
ArgumentError()is raised appropriately when arg parsing fails. It is passed the argument instance and a messageArgumentError()does not store the argument as an instance attribute, despite being passed (which would be convenient)ArgumentErrorexception by subclassingArgumentParser, overriding .error() and getting hold of the exception from sys.exc_info()All that means the following code – whilst ugly – allows us to catch the ArgumentError exception, get hold of the offending argument and error message, and do as we see fit:
Not tested in any useful way. The usual don’t-blame-me-if-it-breaks indemnity applies.