Python-为sys.stdin设置较小的缓冲区大小?

Python-为sys.stdin设置较小的缓冲区大小?,第1张

Python-为sys.stdin设置较小的缓冲区大小?

你可以使用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,如果可能会满足你的要求,则完全删除缓冲在所有平台上应减少出现问题)。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5640910.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存