如何刷新Python打印输出?
我建议五种方法:
在Python 3中,调用 print(..., flush=True) (在Python 2的print函数中不提供flush参数,并且print语句没有模拟) .
在输出文件上调用 file.flush() (我们可以用python 2的print函数来执行此操作),例如, sys.stdout
将此应用于具有部分功能的模块中的每个打印函数调用,
print = partial(print, flush=True) 应用于全局模块 .
将此应用程序应用于传递给interpreter命令的标志( -u )
将此应用于环境中的每个python进程 PYTHONUNBUFFERED=TRUE (并取消设置该变量以撤消此操作) .
Python 3.3
使用Python 3.3或更高版本,您只需提供 flush=True 作为 print 函数的关键字参数:
print('foo', flush=True)
Python 2(或<3.3)
他们没有将 flush 参数反向移植到Python 2.7所以如果你're using Python 2 (or less than 3.3), and want code that'兼容2和3,我可以建议以下兼容性代码 . (注意 __future__ 导入必须位于/非常“靠近top of your module”):
from __future__ import print_function
import sys
if sys.version_info[:2] < (3, 3):
old_print = print
def print(*args, **kwargs):
flush = kwargs.pop('flush', False)
old_print(*args, **kwargs)
if flush:
file = kwargs.get('file', sys.stdout)
# Why might file=None? IDK, but it works for print(i, file=None)
file.flush() if file is not None else sys.stdout.flush()上述兼容性代码将涵盖大多数用途,但对于更彻底的处理,see the six module .
或者,您可以在打印后调用 file.flush() ,例如,使用Python 2中的print语句:
import sys
print 'delayed output'
sys.stdout.flush()将一个模块中的默认值更改为flush = True
您可以在模块的全局范围内使用functools.partial更改打印功能的默认值:
import functools
print = functools.partial(print, flush=True)如果你看看我们新的部分函数,至少在Python 3中:
>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(, flush=True)我们可以看到它像正常一样工作:
>>> print('foo')
foo我们实际上可以覆盖新的默认值:
>>> print('foo', flush=False)
foo再次注意,这只会更改当前的全局范围,因为当前全局范围上的打印名称将掩盖内置 print 函数(或者取消引用兼容性函数,如果使用Python 2,则在当前的全局范围内) .
如果你想在一个函数内而不是在一个模块的全局范围内这样做,你应该给它一个不同的名字,例如:
def foo():
printf = functools.partial(print, flush=True)
printf('print stuff like this')如果在函数中声明它是全局的,那么您将在模块的全局命名空间中更改它,因此您应该将它放在全局命名空间中,除非该特定行为正是您想要的 .
更改进程的默认值
我认为这里最好的选择是使用 -u 标志来获得无缓冲的输出 .
$ python -u script.py要么
$ python -um package.module强制stdin,stdout和stderr完全无缓冲 . 在重要的系统上,还将stdin,stdout和stderr置于二进制模式 . 请注意,file.readlines()和File Objects(对于sys.stdin中的行)中存在内部缓冲,不受此选项的影响 . 要解决此问题,您需要在while 1:循环中使用file.readline() .
更改shell操作环境的默认值
如果将环境变量设置为非空字符串,则可以为环境中的所有python进程或从环境继承的环境获取此行为:
例如,在Linux或OSX中:
$ export PYTHONUNBUFFERED=TRUE或Windows:
C:\SET PYTHONUNBUFFERED=TRUEPYTHONUNBUFFERED如果将其设置为非空字符串,则相当于指定-u选项 .
附录
这是Python 2.7.12中打印函数的帮助 - 请注意,没有 flush 参数:
>>> from __future__ import print_function
>>> help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
















