I'm using Python's fileinput
module to either read data from stdin
or from files passed in as program arguments. That's fine and works well. The problem is I'd like the program to behave differently if there is no input. When there's nothing on stdin
and no program arguments, stdin
reads data from the console i.e. it becomes interactive. That is the state I'd like to detect. fileinput
doesn't advertise any tools for helping here. There are methods to determine if the current line is a file or stream (e.g. isstdin
).
Using other answers, and poking around the internals of fileinput
, I've got something that works, but it relies on FileInput._files
which feels like something I shouldn't be using:
import sys, fileinput
def has_lines():
lines = fileinput.input()
return (lines._files != ('-',) or not sys.stdin.isatty()), lines
# ^ ^
# | |
# Concerned about referring to internals |
# Returns false if there's something in stdin
existing_input, lines = has_lines()
if existing_input:
for line in lines:
pass #Batch processing mode
else:
pass #Interactive mode
Can I detect interactive mode without poking around the internals of a FileInput
object?