他们没有将 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()
>>> 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.
14 回答
同样如this blog中所建议的那样,可以在非缓冲模式下重新打开
sys.stdout
:之后将自动刷新每个
stdout.write
和print
操作 .我建议五种方法:
在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
函数的关键字参数: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”):上述兼容性代码将涵盖大多数用途,但对于更彻底的处理,see the six module .
或者,您可以在打印后调用
file.flush()
,例如,使用Python 2中的print语句:将一个模块中的默认值更改为flush = True
您可以在模块的全局范围内使用functools.partial更改打印功能的默认值:
如果你看看我们新的部分函数,至少在Python 3中:
我们可以看到它像正常一样工作:
我们实际上可以覆盖新的默认值:
再次注意,这只会更改当前的全局范围,因为当前全局范围上的打印名称将掩盖内置
print
函数(或者取消引用兼容性函数,如果使用Python 2,则在当前的全局范围内) .如果你想在一个函数内而不是在一个模块的全局范围内这样做,你应该给它一个不同的名字,例如:
如果在函数中声明它是全局的,那么您将在模块的全局命名空间中更改它,因此您应该将它放在全局命名空间中,除非该特定行为正是您想要的 .
更改进程的默认值
我认为这里最好的选择是使用
-u
标志来获得无缓冲的输出 .要么
来自docs:
更改shell操作环境的默认值
如果将环境变量设置为非空字符串,则可以为环境中的所有python进程或从环境继承的环境获取此行为:
例如,在Linux或OSX中:
或Windows:
来自docs:
附录
这是Python 2.7.12中打印函数的帮助 - 请注意,没有
flush
参数:默认打印打印到
sys.stdout
.参考文献:
http://docs.python.org/reference/simple_stmts.html#the-print-statement
http://docs.python.org/library/sys.html
http://docs.python.org/library/stdtypes.html#file-objects
从Python 3.3开始,你可以强制普通的
print()
函数进行刷新而不需要使用sys.stdout.flush()
;只需将"flush"关键字参数设置为true即可 . 来自the documentation:使用Python 3.x,
print()
函数已被扩展:所以,你可以这样做:
Python Docs Entry
我在Python 3.4中这样做了:
使用
-u
命令行开关可以工作,但它有点笨拙 . 这意味着如果用户在没有-u
选项的情况下调用脚本,程序可能会出现错误行为 . 我通常使用自定义stdout
,如下所示:...现在所有
print
调用(隐式使用sys.stdout
)将自动flush
编辑 .丹的想法并不奏效:
结果:
我相信问题是它继承自文件类,实际上并不是必需的 . 根据sys.stdout的文档:
如此变化
至
让它工作得很好 .
在Python 3中,您可以覆盖打印功能,默认设置为
flush = True
运行
python -h
,我看到一个命令行选项:这是relevant doc .
为什么不尝试使用无缓冲的文件?
要么
这是我的版本,它也提供了writelines()和fileno():
喜欢Dan的解决方案!对于python3做: