目前,当我
从 __future__ 导入 print_function
从 Python 2.7.6 开始,我显然在添加 flush
关键字参数之前得到了一个 print() 版本,根据 docs,它进入了 Python 3.3。 .我的系统(Ubuntu)安装的Python3是Python 3.4,我验证了它的print()函数有flush
参数。
如何从 3.4 导入 print()
函数?
__future__
从哪里获得旧的打印功能?
最佳答案
您无法将 3.4 的版本导入到 Python 2.7 中,不。打印后手动刷新 sys.stdout
:
import sys
print(...)
sys.stdout.flush()
或者,如果您必须接受关键字参数,您可以围绕 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()
这将创建一个与 3.3 及更高版本中的版本相同的替代版本。
关于python - 需要来自 __future__ 的 print() 的 Python 3.4 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27991443/