I'd like to use the
From the source documentation:
ArgumentError: The exception raised by ArgumentParser objects when there are errors with the parser's actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.
argument parameter of the constructor is the
Action object from which the exception is raised. Usually there is no need to raise it outside of an
Action subclass, and when subclassing it, there is no need to raise it explicitly; you usually raise
ValueError (or whatever is appropriate) instead.
In regards to your comment, that you only want to accept floating point values between 0 and 1. For this you should use the ability to define custom types. You can do it for example like this:
def percentFloat ( string ): value = float( string ) if value < 0 or value > 1: raise argparse.ArgumentTypeError( 'Value has to be between 0 and 1' ) return value parser = argparse.ArgumentParser() parser.add_argument( 'test', type=percentFloat ) parser.parse_args()
Note that this is also safe against non-floats as
float( string ) will raise a
ValueError for non-floats which also triggers an invalid type error by the
ArgumentTypeError is just a way to specify a custom error message.
For mutually exclusive parameters, you should use
Parameter dependency isn’t really something that should be done by the argument parser. For semantic details, you should instead simply do it yourself:
args = parser.parse_args() if args.w and not args.p: parser.error( '-p is required when -w is set.' )
Here I've used
parser.error to exit with status 2, give an error message and also automatically print the usage.
But of course in such a basic situation it would make a lot more sense just to implicitly guess
-p if possible.