0

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?

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
  • "When there's nothing on `stdin` and no program arguments, `stdin` reads data from the console" - Input via the console is just as much `stdin` as `stdin` being connected to anything else (a file, a pipe to another process, etc.). Aside from the latency (which any old pipe to another process *might* exhibit), there is nothing unique about being connected to the console. I feel like you have [an XY problem](https://meta.stackexchange.com/q/66377/322040), because it usually shouldn't matter what `stdin` is connected to. – ShadowRanger Oct 04 '18 at 01:23
  • I see what you're saying. Perhaps I am asking the wrong question. I can see there are a few parts to the question. Determining if I'm on an interactive TTY is part of it, determining if there are files in the program arguments is another. I guess I the issue is between fileinput (which hides a bunch of implementation), and TTY input (which fileinput doesn't cater for out of the box). – Alex Taylor Oct 04 '18 at 01:30
  • To be clear, `fileinput` hides a bunch of implementation for a reason. It's intended for simple use cases (and to make Perl folks who love `while (<>) {` comfortable switching). If you're looking at digging into the messy details, it's a good chance your program should be implementing its own argument parsing and file opening/handling (e.g. with `argparse` to aid), so you have the control you need. – ShadowRanger Oct 04 '18 at 01:33
  • So, in your opinion, `fileinput` is the wrong tool for the job? – Alex Taylor Oct 04 '18 at 01:55

0 Answers0