I found the very useful syntax
parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default='-')
for specifying an input file or using stdin—both of which I want in my program. However, the input file is not always required. If I'm not using -i
or redirecting input with one of
$ someprog | my_python_prog $ my_python_prog < inputfile
I don't want my Python program to wait for input. I want it to just move along and use default values.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
Metavar: It provides a different name for optional argument in help messages.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
The standard library documentation for argparse suggests this solution to allow optional input/output files:
>>> parser = argparse.ArgumentParser() >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), ... default=sys.stdin) >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), ... default=sys.stdout) >>> parser.parse_args(['input.txt', 'output.txt']) Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>) >>> parser.parse_args([]) Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With