Pet*_*ete 4 python printing flush python-2.7 python-3.x
目前,当我
from __future__ import print_function
从Python 2.7.6开始,我显然在添加flush关键字参数之前得到了print()版本,根据文档在Python 3.3中进行了操作.我的系统(Ubuntu)中安装的Python3是Python 3.4,我验证了它的print()函数有flush参数.
如何print()从3.4 导入功能?从哪里__future__获得较旧的打印功能?
Mar*_*ers 10
你无法将3.4中的版本导入Python 2.7,没有.sys.stdout打印后只需手动冲洗:
import sys
print(...)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
或者你可以创建一个包装器函数,print()如果你必须有一些接受关键字参数的东西:
from __future__ import print_function
import sys
try:
# Python 3
import builtins
except ImportError:
# Python 2
import __builtin__ as builtins
def print(*args, **kwargs):
sep, end = kwargs.pop('sep', ' '), kwargs.pop('end', '\n')
file, flush = kwargs.pop('file', sys.stdout), kwargs.pop('flush', False)
if kwargs:
raise TypeError('print() got an unexpected keyword argument {!r}'.format(next(iter(kwargs))))
builtins.print(*args, sep=sep, end=end, file=file)
if flush:
file.flush()
Run Code Online (Sandbox Code Playgroud)
这将创建一个替换版本,其工作方式与3.3及更高版本的版本相同.