read(size=-1, /) method of _io.TextIOWrapper instanceRead at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.If n is negative or omitted, read until EOF.
input(prompt=None, /)Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without atrailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.On *nix systems, readline is used if available.
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:source = sys.stdin.bufferelse:# Python 2 on Windows opens sys.stdin in text mode, and# binary data that read from it becomes corrupted on \r\nif sys.platform == "win32":# set sys.stdin to binary modeimport os, msvcrtmsvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)source = sys.stdin
b = source.read()
import sysimport select
# select(files to read from, files to write to, magic, timeout)# timeout=0.0 is essential b/c we want to know the asnwer right awayif select.select([sys.stdin], [], [], 0.0)[0]:help_file_fragment = sys.stdin.read()else:print("No data passed to stdin", file=sys.stderr)sys.exit(2)
# pipe.py
import os, sys, time
os.set_blocking(0, False)sys.stdin = os.fdopen(0, 'rb', 0)sys.stdout = os.fdopen(1, 'wb', 0)
while 1:time.sleep(.1)try: out = sys.stdin.read()except:sys.stdout.write(b"E")continueif out is None:sys.stdout.write(b"N")continueif not out:sys.stdout.write(b"_")break# working..out = b"<" + out + b">"sys.stdout.write(out)
sys.stdout.write(b".\n")
用法:
$ for i in 1 2 3; do sleep 1; printf "===$i==="; done | python3 pipe.pyNNNNNNNNN<===1===>NNNNNNNNN<===2===>NNNNNNNNN<===3===>_.
最小代码:
import os, sys
os.set_blocking(0, False)fd0 = os.fdopen(0, 'rb', 0)fd1 = os.fdopen(1, 'wb', 0)
while 1:bl = fd0.read()if bl is None: continueif not bl: breakfd1.write(bl)