如何刷新 Python print 的输出?
我提出了五种方法:
- 在 Python 3 中,调用
print(..., flush=True)(flush 参数在 Python 2 的 print 函数中不可用,并且 print 语句没有类似物)。
- 在输出文件上调用
file.flush()(我们可以包装python 2的打印函数来做到这一点),例如sys.stdout
- 将此应用于模块中具有部分函数的每个打印函数调用,
print = partial(print, flush=True) 应用于模块全局。
- 将此标志应用于进程,并将标志 (
-u) 传递给解释器命令
- 使用
PYTHONUNBUFFERED=TRUE 将此应用于您环境中的每个python 进程(并取消设置变量以撤消此操作)。
Python 3.3+
使用 Python 3.3 或更高版本,您只需将 flush=True 作为关键字参数提供给 print 函数即可:
print('foo', flush=True)
Python 2(或
他们没有将 flush 参数反向移植到 Python 2.7 因此,如果您使用的是 Python 2(或低于 3.3),并且想要与 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(<built-in function print>, 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
来自docs:
强制标准输入、标准输出和标准错误完全无缓冲。在重要的系统上,还要将 stdin、stdout 和 stderr 置于二进制模式。
请注意,file.readlines() 和文件对象(用于 sys.stdin 中的行)中有内部缓冲,不受此选项影响。要解决这个问题,您需要在 while 1: 循环中使用 file.readline()。
更改 shell 运行环境的默认值
如果将环境变量设置为非空字符串,则可以为环境中的所有 python 进程或从环境继承的环境获取此行为:
例如,在 Linux 或 OSX 中:
$ export PYTHONUNBUFFERED=TRUE
或 Windows:
C:\SET PYTHONUNBUFFERED=TRUE
来自docs:
PYTHONUNBUFFERED
如果设置为非空字符串,则相当于指定 -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.