如果fd是bash shell,如何避免行缓冲问题?
最佳答案
这似乎有效:
#!/usr/local/cpython-3.3/bin/python
import os
import pty
#mport sys
import fcntl
OFLAGS = None
def set_nonblocking(file_handle):
"""Make a file_handle non-blocking."""
global OFLAGS
OFLAGS = fcntl.fcntl(file_handle, fcntl.F_GETFL)
nflags = OFLAGS | os.O_NONBLOCK
fcntl.fcntl(file_handle, fcntl.F_SETFL, nflags)
def main():
(pid, file_handle) = pty.fork()
if pid == 0:
# we're in the child
os.execl('/bin/sh', '/bin/sh', '-i')
else:
#file_handle = os.open('/dev/null', os.O_RDONLY)
set_nonblocking(file_handle)
while True:
try:
# return 1-n bytes or exception if no bytes
data = os.read(file_handle, 1024)
except BlockingIOError:
#sys.stdout.write('no data read\r')
pass
else:
print(len(data), data)
main()
有时,处理非阻塞 I/O 的方法是使用线程或子进程,顺便说一句。然后一个线程或子进程可以阻塞,而其他线程或子进程则可以愉快地工作。
HTH
关于Python:os.read() 在 fd 上阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457648/