python - 禁用输出缓冲

标签 python stdout output-buffering

Python 的解释器是否默认为 sys.stdout 启用输出缓冲?

如果答案是肯定的,那么禁用它的方法有哪些?

到目前为止的建议:

  1. 使用-u命令行开关
  2. sys.stdout 包装在每次写入后刷新的对象中
  3. 设置PYTHONUNBUFFERED环境变量
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

有没有其他方法可以在执行期间以编程方式在 sys/sys.stdout 中设置一些全局标志?


如果您只想在使用print 的特定写入之后刷新,请参阅How can I flush the output of the print function? .

最佳答案

来自 Magnus Lycka answer on a mailing list :

You can skip buffering for a whole python process using python -u or by setting the environment variable PYTHONUNBUFFERED.

You could also replace sys.stdout with some other stream like wrapper which does a flush after every call.

class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'

关于python - 禁用输出缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667615/

相关文章:

python - 在python和appium中,为什么不能使用send_keys()到输入框

python - 如果 python pandas 中存在条件,如何用前一列值设置或替换行值

python - 当我使用 Selenium Webdriver 时,Geckodriver 正在创建 rust_mozprofile 目录

python - 查询自引用列表关系以检索多个级别的 child

c - 如何使用 C 将所有内容从我的终端复制到一个文件,包括标准输出和提示符?

php - 输出缓冲区错误处理

c - 创建和打开 FIFO 后 fprintf() 到 stdout 不工作

python - 如何将标准输出和标准错误重定向到 Python 中的记录器

optimization - 从长时间运行的进程中写入大量文件?

无论缓冲区设置如何,PHP 命令行输出缓冲区输出