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.

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'>)

Use isatty to detect whether your program is in an interactive session or reading from a file:

if not sys.stdin.isatty(): # Not an interactive device.
  # ... read from stdin

However, for the sake of consistency and reproducability, consider following the norm and reading from stdin if the filename is -. You may want to consider to let the fileinput module handle that.


Need Your Help

What are the standards for security on the web and web development?

security standards

What are the standards that govern security practices on the web and web development? What standards body publishes such documents?

CSS 'active' does not work when converting HTML to PHP include

php css navigation hyperlink hover

I realize a 'similar' question was asked but the other user is using a much different approach than I am. I am simply trying to include an HTML navigation on my PHP pages for easier modification do...