python - 需要来自 __future__ 的 print() 的 Python 3.4 版本

标签 python python-2.7 python-3.x printing flush

目前,当我

从 __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/

相关文章:

Python 检查将方法识别为 FunctionType 而不是 types.MethodType

python - 将TBB与OpenCV和Python(Eclipse)结合使用

python - Pandas 字符串按字符转换为整数

python - 连续输入序列的简单哈希,输出中没有可见的循环

python - 如何在 Python 中并行检查多个列表中是否存在某个项目?

sql-server - 无法在 Scintific Linux 7.5 上使用 pyodbc 连接到 MS SQL Server

python - 如何将元组转换为字典?

python-3.x - 没有名为套接字的模块

python - 将列表元素拆分为键/值字典

javascript - 如何向 Flask Server 发送数据?