简体   繁体   English

Python刷新打印语句

[英]Python flush a print statement

I recenlty desired a bit of python code that would allow me to output to the console and a logfile with the same print statement. 我很想得到一些Python代码,该代码允许我将输出到控制台和具有相同print语句的日志文件输出。 After googleing I found this website which offered an excellent solution. 谷歌搜索后,我发现这个网站提供了一个很好的解决方案。 However, I would like to be able to flush the output buffer after each write in order to see it in the log file. 但是,我希望能够在每次写入后刷新输出缓冲区,以便在日志文件中看到它。 How would I go about adding it into this class? 我将如何将其添加到该类中?

I have tried to following setups... 我试图按照以下设置进行操作...

class output_file(object):
  def __init__(self, stdout, filename):
    silentremove(filename)
    self.stdout = stdout
    self.logfile = open(filename, "a")

def write(self, text):
    self.stdout.write(text)
    self.logfile.write(text)
    sys.stdout.flush()

  def flush(self):
    sys.stdout.flush()

  def close(self):
    self.stdout.close()
    self.logfile.close()

This was had a cyclic error which resulted in the flush function calling itself. 这是一个周期性错误,导致flush函数调用自身。

class output_file(object):
  def __init__(self, stdout, filename):
    silentremove(filename)
    self.stdout = stdout
    self.logfile = open(filename, "a")

  def write(self, text):
    self.stdout.write(text)
    self.logfile.write(text)
    self.stdout.flush()

  def flush(self):
    sys.stdout.flush()

  def close(self):
    self.stdout.close()
    self.logfile.close()

This didn't flush it at all. 这根本没有冲洗它。

The following reopens sys.stdout in unbuffered mode. 以下内容以无缓冲模式重新打开sys.stdout。 Each stdout.write and print will be automatically flushed (ie printed to stdout) afterwards. 之后,每个stdout.writeprint都会自动刷新(即打印到stdout)。

import sys
import os

# Flush STDOUT continuously
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

The third argument of os.fdopen is the buffering argument, 0 is unbuffered, 1 is line buffered and >1 will result in a buffer of (approximately) that size (in bytes), <0 will use the systems default. os.fdopen的第三个参数是缓冲参数, 0是未缓冲的, 1是行缓冲的, >1将导致(大约)大小(以字节为单位)的缓冲区, <0将使用系统默认值。

UPDATE UPDATE

With Python 3 unbuffered text is not allowed, ie the following 使用Python 3时,不允许使用非缓冲文本,即以下内容

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Will result in the error 会导致错误

ValueError: Can't have unbuffered text I/O

To use unbuffered I/O in python3, bytes can be used, ie 要在python3中使用无缓冲的I / O,可以使用字节,即

sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)

Will work fine in python3. 在python3中可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM