When using argparse
I have to add an extra step to make sure there is a input (either from stdin or file).
import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
args = parser.parse_args()
# taking input from stdin which is empty, so there is neither a stdin nor a file as argument
if sys.stdin.isatty() and args.infile.name == "<stdin>":
sys.exit("Please give some input")
with args.infile as file:
print(file.read())
If I use default=(None if sys.stdin.isatty() else sys.stdin)
instead of default=sys.stdin
, then I have to use the following if
block to make sure there is a input (either from stdin or file):
if args.infile is None:
sys.exit("Please give some input")
Instead of:
if sys.stdin.isatty() and args.infile.name == "<stdin>":
sys.exit("Please give some input")
Is there anyway by using parser.add_argument
, I can get rid of this if
block. For example, by saying “if there is no stdin then must take one argument”.
I want to get rid of this if
block and use parser.add_argument
only so that the help generates properly.