views:

137

answers:

2

in python,how to check sys.stdin has data or not, i found os.isatty(0) only can check is connect to a tty device,but if some one use code like

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

after that use os.isatty(0) it's still return True,

what i need is check from stdin is have data,any advice is welcome

+2  A: 

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.

Rakis
this is exactly what i need,thanks
mlzboy
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
@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
@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
A: 

Depending on the goal here:

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

can also be useful.

Gregg Lind
AFAIK,the fileinput has a disadvantge which limited the args must the filename,but my args may be some control command,
mlzboy
Fair enough! I was trying to handle the common idiom of "do something to a bunch of lines, possibly from stdin" :)
Gregg Lind