I want to specify a required argument called inputdir
but I also would like to have a shorthand version of it called i
. I don't see a concise solution to do this without making both optional arguments and then doing my own check. Is there a preferred practice for this that I'm not seeing or the only way is to make both optional and do my own error-handling?
Here is my code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputdir", help="Specify the input directory")
parser.parse_args()
For flags (options starting with
-
or--
) pass in options with the flags. You can specify multiple options:See the name or flags option documentation:
Demo:
However, the first element for required arguments is just a placeholder.
-
and--
options are always optional (that's the command line convention), required arguments are never specified with such switches. Instead the command-line help will show where to put required arguments with a placeholder based on the first argument passed toadd_argument()
, which is to be passed in without dashes.If you have to break with that convention and use an argument starting with
-
or--
that is required anyway, you'll have to do your own checking:Here the
parser.error()
method will print the help information together with your error message, then exit.