I'd like to use argparse
to read from either stdin
or an input file. In other words:
I'm asking for behavior similar to what's described in this question, but I want argparse
to recognize no file as a failed input.
I would recommend just settings nargs='?'
and then handling the case of a Nonetype separately. According to the official documentation, "FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects". So just give it a dash if you want stdin.
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('inputfile', nargs='?', type=argparse.FileType('r'))
if not inputfile:
sys.exit("Please provide an input file, or pipe it via stdin")
Using the information from the question you linked to, what about using sys.stdin.isatty()
to check if the instance your program is being run is part of a pipeline, if not, read from input file, otherwise read from stdin
. If the input file does not exist or stdin
is empty throw an error.
Hope that helped.
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