87

In Python, how do you check if sys.stdin has data or not?

I found that os.isatty(0) can not only check if stdin is connected to a TTY device, but also if there is data available.

But if someone uses code such as

sys.stdin = cStringIO.StringIO("ddd")

and after that uses os.isatty(0), it still returns True. What do I need to do to check if stdin has data?

AppleDash
  • 1,544
  • 2
  • 13
  • 27
mlzboy
  • 14,343
  • 23
  • 76
  • 97
  • 3
    what exactly you want to achieve ? – shahjapan Sep 21 '10 at 17:36
  • That's happening because `os.isatty(0)` checks if the file associated to the file descriptor (fd) 0 is a TTY. When you change the `sys.stdin` variable, you're not changing the file associated with fd0. fd0 is still pointing to the original stdin (which is a TTY in your case). – Cristian Ciupitu Sep 21 '10 at 17:46
  • 2
    Check [this answer](http://stackoverflow.com/questions/3731681/capturing-user-input-at-arbitrary-times-in-python/3732001#3732001). Does it pertain to your question? – Muhammad Alkarouri Sep 21 '10 at 18:06
  • @Cristian Ciupitu,you are right,i use sys.stdin=cStringIO.String("ddd") to redirect the stdin,what i want is how to check sys.stdin is have data,if i use sys.stdin.read() directly it will block the below thing and wait always if no input given – mlzboy Sep 21 '10 at 22:59
  • I fail to see how reading from `cStringIO.StringIO("ddd")` could block; it always has data available, except when EOF is reached of course. – Cristian Ciupitu Sep 21 '10 at 23:19
  • http://stackoverflow.com/questions/3762881/how-do-i-check-if-stdin-has-some-data – Jared Goguen Feb 07 '16 at 03:36
  • It would be interesting to know how you _found that `os.isatty(0)` can not only check if stdin is connected to a TTY device, but also if there is data available._ – Armali Oct 19 '17 at 06:14

7 Answers7

94

On Unix systems you can do the following:

import sys
import select

if select.select([sys.stdin, ], [], [], 0.0)[0]:
    print("Have data!")
else:
    print("No data")

On Windows the select module may only be used with sockets though so you'd need to use an alternative mechanism.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Rakis
  • 7,779
  • 24
  • 25
  • i'm sorry i have to remove the accept,because i use sys.stdin=cStringIO.StringIO("ddd") redirect the stdin to a mock file,but it didn't have fileno method,it i use you code it will raise if not select.select([sys.stdin],[],[],0.0)[0]: TypeError: argument must be an int, or have a fileno() method. – mlzboy Sep 21 '10 at 22:52
  • 2
    @mlzboy: only "real" files, opened by the operating system have a file descriptor number (btw on Unix sockets or pipes are files too). `select` which calls the operating system's select function can work only with those files. `StringIO` is a virtual file known only to the Python interpreter therefore it doesn't have a file descriptor and you can't use `select` on it. – Cristian Ciupitu Sep 21 '10 at 23:23
  • @Cristian Ciupitu thank you i got it,finally i use pipe replace StringIO,here is the code,may be help others r="\n".join(dict["list_result"].split("\n")[:i]) fdr,fdw=os.pipe() os.write(fdw,r) os.close(fdw) f=os.fdopen(fdr) sys.stdin=f – mlzboy Sep 22 '10 at 01:48
  • 2
    @mlzboy pipes have a limited buffer size. Writing to a pipe with nothing reading from it is dangerous because if you try to write more than the buffer size it will block (deadlock). – Aryeh Leib Taurog Jul 15 '14 at 13:11
  • 1
    This method failed for me when used in a script that was executed by cron. `sys.stdin.isatty()` however did work for me within cron. – Dave Jun 29 '16 at 00:13
  • 1
    Does not work in Jenkins, returns ``<_io.TextIOWrapper name='' mode='r' encoding='UTF-8'>`` and not ``[]`` – GuySoft Dec 04 '16 at 11:36
  • This is dangerous. If the script is run with `/dev/null` as stdin, select.select will immediately return. This is the case when running the script via cron or other tools. The easiest way to replicate this behavior is to add `< /dev/null` on the command line. – andyn Nov 27 '18 at 11:42
  • This method tests only whether `sys.stdin` has data that are *immediately* available. And I don't think that is strictly guaranteed even when it is connected to a file (e.g. what if it is connected to a file on an NFS and the underlying network connection is spotty?). `select` is meant for multiplexing, i.e. choosing whatever is ready to read/write from multiple sources/destinations. – musiphil Feb 27 '19 at 18:14
90

I've been using

if not sys.stdin.isatty()

Here's an example:

import sys

def main():
    if not sys.stdin.isatty():
        print "not sys.stdin.isatty"
    else:
        print "is  sys.stdin.isatty"

Running

$ echo "asdf" | stdin.py
not sys.stdin.isatty

sys.stdin.isatty() returns false if stdin is not connected to an interactive input device (e.g. a tty).

isatty(...)
    isatty() -> true or false. True if the file is connected to a tty device.
vy32
  • 28,461
  • 37
  • 122
  • 246
Aaron
  • 2,344
  • 3
  • 26
  • 32
  • 6
    Thanks! This is so much easier than using `select`. – Niklas R Oct 25 '14 at 08:05
  • Thanks. That solved my: echo 'maybe pipe' | stdin.py +maybe_args on linux. Does melancholynaturegirl's solution work on windows? – Alexx Roche Jun 02 '15 at 18:15
  • so it seems... C:\Users\naturegirl\Desktop>C:\Python27\python.exe isatty.py is sys.stdin.isatty C:\Users\naturegirl\Desktop> C:\Users\naturegirl\Desktop>echo "foo" | C:\Python27\python.exe isatty.py not sys.stdin.isatty – Aaron Jun 02 '15 at 22:30
  • 36
    This is not a good idea. What if stdin is being piped in from a file? isatty() is telling you if stdin is coming in directly from a terminal, not if there is more data to read from stdin – Lathan Jul 24 '15 at 21:35
  • 2
    Since `grep` is mentioned in another post, I'll mention that `less` uses `isatty`. I came here looking to do something like `less`: read input from a file if a file path is given as an input argument, but read input from stdin otherwise. An alternative is to use `-` as an alias for stdin and just accept the file argument. – ws_e_c421 Mar 22 '18 at 18:22
  • I think this answers whether the input comes from a "human typing on a terminal who will then press Ctrl+D to send the input" or some "data stream" (stdin from pipe, file, etc.), whereas the other post with `select` answers whether the "data stream" has any more data in it. – user Jun 08 '20 at 18:32
  • Exactly what i want. Either pipe in some data or do default stuff... – Franz Knülle Mar 22 '23 at 10:23
4

Depending on the goal here:

import fileinput
for line in fileinput.input():
    do_something(line)

can also be useful.

Gregg Lind
  • 20,690
  • 15
  • 67
  • 81
  • AFAIK,the fileinput has a disadvantge which limited the args must the filename,but my args may be some control command, – mlzboy Sep 22 '10 at 12:05
  • Fair enough! I was trying to handle the common idiom of "do something to a bunch of lines, possibly from stdin" :) – Gregg Lind Sep 22 '10 at 19:35
3

As mentioned by others, there's no foolproof way to know if data will become available from stdin, because UNIX doesn't allow it (and more generally because it can't guess the future behavior of whatever program stdin connects to).

Always wait for stdin, even if there may be nothing (that's what grep etc. do), or ask the user for a - argument.

Neuron
  • 5,141
  • 5
  • 38
  • 59
n.caillou
  • 1,263
  • 11
  • 15
  • 1
    So, you're answering a question by referring to the very same question? WTF?? – ForceBru Apr 18 '17 at 20:53
  • @ForceBru This is indeed very confusing, haha. It would seem that another question was merged here. I have edited. – n.caillou Apr 19 '17 at 00:16
  • What would the process be - wait for stdin and read until an EOF, then process the data? That is, how do grep et al. know when to process data and when to quit? – Matt Jul 12 '17 at 14:38
  • 1
    @Matt the upstream data source is responsible for sending EOF. e.g. `printf "" | cat` or `while read l; do true; done; echo finishing` (in the second case you have to input EOF/^D manually to go through) – n.caillou Jul 12 '17 at 20:52
  • _p.s._ Note that if you enter just e.g. `cat` on the command line, it will wait for input indefinitely. In the above example printf sends EOF – n.caillou Jul 12 '17 at 21:12
  • Did you mean to say "because Windows doesn't allow it?" (Unix certainly does allow it) – Jeremy Friesner Aug 28 '18 at 00:02
  • @JeremyFriesner Content may only become available after a while. – n.caillou Aug 30 '18 at 05:17
  • @n.caillou certainly -- however, under Unix you can use `select()` (or `poll()` or etc) to find out if there is data to read on stdin. You can do it either as an instantaneous-poll (by setting the timeout parameter to 0), or you can have `select()` block until data is ready, and then return. On Unix-based OS's, STDIN_FILENO behaves more or less the same as any other socket or file descriptor (whereas on Windows, you're mostly out-of-luck -- your only option is to work-around the problem by spawning a separate thread to read from stdin and pass the data back to the main thread via a socket) – Jeremy Friesner Aug 30 '18 at 19:13
  • @JeremyFriesner Actually, I think this is another byproduct of the merging mentioned in another comment. The context for my answer has gone missing; I'll try to clarify it. We agree that UNIX lets you know if there is anything in stdin at the moment, and if stdin is connected to a terminal. – n.caillou Aug 31 '18 at 16:31
0

I found a way to use a future from concurrent.futures library. This is a gui program that will allow you to scroll and hit the wait button when you are still waiting for STDIN. Whenever the program sees it has a line of information from STDIN then it will print it in the multi-line box. But it does not lock the script lock out the user from the gui interface why it is checking stdin for a new line. (Please note I tested this in python 3.10.5)

import concurrent.futures
import PySimpleGUI as sg
import sys

def readSTDIN():
    return sys.stdin.readline()

window = sg.Window("Test Window", [[sg.Multiline('', key="MULTI", size=(40, 10))],
                                   [sg.B("QUIT", bind_return_key=True, focus=True),
                                    sg.B("Wait")]], finalize=True, keep_on_top=True)
for arg in sys.argv[1:]:
    window["MULTI"].print(f"ARG={arg}")
with concurrent.futures.ThreadPoolExecutor() as pool:
    futureResult = pool.submit(readSTDIN)
    while True:
        event, values = window.read(timeout=500)
        if event != "__TIMEOUT__":
            window['MULTI'].print(f"Received event:{event}")
        if event in ('QUIT', sg.WIN_CLOSED):
            print("Quit was pressed")
            window.close()
            break
        if futureResult.done(): # flag that the "future" task has a value ready;
                                #therefore process the line from STDIN
            x = futureResult.result()
            window["MULTI"].print(f"STDIN:{x}")
            futureResult = pool.submit(readSTDIN) #add a future for next line of STDIN
RAllenAZ
  • 36
  • 4
-1

Saw a lot of answers above, in which almost all the answers required either sys, select, os, etc. However, I got a very simple idea about how continuously to take input from stdin if it has data. We can use try, except block to do so. as,

while(1):
  try:
    inp = input()
  except:
     break

The above loop will run and we are checking for input continuously and storing the input in variable "inp", if there is no input in the stdin then try will throw an error however in except block break statement is present, so the while loop will be terminated

soraku02
  • 282
  • 3
  • 11
-2

Using built in modules this can be achieved with following code as Gregg gave already the idea:

import fileinput
isStdin = True
for line in fileinput.input:
    # check if it is not stdin
    if not fileinput.isstdin():
        isStdin = False
        break
    # continue to read stdin
    print(line)
fileinput.close()
Neuron
  • 5,141
  • 5
  • 38
  • 59
Hüseyin
  • 17
  • 4