Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional stdin in Python with argparse

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.

like image 497
Justin Force Avatar asked Sep 27 '11 22:09

Justin Force


People also ask

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Metavar in Argparse Python?

Metavar: It provides a different name for optional argument in help messages.

What is Argparse ArgumentParser ()?

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.

What does Nargs do in Argparse?

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.


1 Answers

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'>) 
like image 108
mikewaters Avatar answered Oct 15 '22 16:10

mikewaters