你可以使用python的
-u标志从
stdin / stdout完全删除缓冲:
-u : unbuffered binary stdout and stderr (also PYTHonUNBUFFERED=x) see man page for details on internal buffering relating to '-u'
手册页阐明了:
-u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xread- lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.除此之外,不支持更改现有文件的缓冲,但是可以使用
os.fdopen来创建一个新文件对象,该文件对象具有与现有文件相同的基础文件描述符,并且可能使用不同的缓冲。即
import osimport sysnewin = os.fdopen(sys.stdin.fileno(), 'r', 100)
应该绑定newin到读取与标准输入相同的FD的文件对象的名称,但是一次只能缓冲大约100个字节(并且你可以继续
sys.stdin = newin从此开始使用新的文件对象作为标准输入)。我说“应该”,因为这方面的使用有一些平台上的一些错误和问题的(这是相当困难的功能,提供跨平台的全通用) -我不知道它的状态是什么了,但我” d绝对建议在所有感兴趣的平台上进行全面测试,以确保一切顺利。(-u,如果可能会满足你的要求,则完全删除缓冲在所有平台上应减少出现问题)。



