Need Python 3.4 version of print() from __future__

天涯浪子 提交于 2019-11-28 08:44:09

问题


Currently, when I

from __future__ import print_function

from Python 2.7.6, I apparently get a version of print() prior to the addition of the flush keyword argument, which went in Python 3.3 according to the docs. The Python3 installed in my system (Ubuntu) is Python 3.4, and I verified its print() function has the flush argument.

How do I import the print() function from 3.4? From where is __future__ getting the older print function?


回答1:


You cannot get the version from 3.4 imported into Python 2.7, no. Just flush sys.stdout manually after printing:

import sys

print(...)
sys.stdout.flush()

Or you can create a wrapper function around print() if you have to have something that accepts the keyword argument:

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()

This creates a replacement version that'll work just the same as the version in 3.3 and up.



来源:https://stackoverflow.com/questions/27991443/need-python-3-4-version-of-print-from-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!