我发现如果我使用 Python 2.7.11,我不能在新打印函数中使用 flush
参数。我用过:
from __future__ import print_function
print('Hello', flush=True)
但它提示错误:
Traceback (most recent call last):
File "print_future.py", line 3, in <module>
print('Hello', flush=True)
TypeError: 'flush' is an invalid keyword argument for this function
看了the documentation for print
之后我发现即使它是一个参数,它也不起作用。我的推断是它不起作用,因为 flush
仅在 3.3 版中添加,因此特殊的 from __future__ import
语句可能正在导入该函数的旧版本。评论表明它使用的是 2.7.11,但我不明白为什么要这样做。
我确实看到了 Need Python 3.4 version of print() from __future__ ,其答案只是包装 print
并手动添加 flush
参数。尽管这行得通,但它似乎更像是一种黑客攻击,而不是解决真正的问题,即我们没有最新版本的打印品。
有没有办法将特定版本的 Python 函数(特别是我想使用 Python 3.5 print
函数)导入我当前的 Python 脚本?如果这是不可能的,为什么不呢?
尽管我写了这个问题,但人们似乎(令人惊讶地)不清楚我的问题有何不同。我会换种说法。
- 看来我的问题是它导入了我不期望的 python 函数(因为它没有找到 flush 参数)。因此,最自然也是我想知道的第一件事是,它导入了哪个打印功能。评论建议它使用 2.7.11,但我不明白为什么要这样做。
- 我知道 from future 语句改变了我的编译器的工作方式。我似乎假设,因为它是一个 future 的声明,它也从 future 的版本中引入了打印功能。看来它只会改变我的解释器的行为。如果我能够看到它使用的打印函数,我就会知道它不会从 future 版本中导入函数,而只是充当 future 的 python 解释器。看起来是这样,但我不确定,我想确切地知道发生了什么。
- 最后但同样重要的是,是否没有一种自然的方法可以将 future 的 python 函数导入我当前的 python 脚本?我想使用 python 3.5 print 语句,除了使编译器表现得像 future 的 python 解释器而且表现得像 future 的 python 版本之外,是否不能使用该功能?让解析器像 future 的 python 但仍然像 2.7.11 一样(至少对我而言)是违反直觉的。我想要的解决方案不是包装器,而是最近 python 的导入。如果这是不可能的,那么我的问题的答案应该解释为什么它不可能。
最佳答案
-
its importing the python function that I am not expecting
我不明白为什么,这是
print
的版本 that's documented in 2.7.x .which print function is it importing.
与 2.7.11 捆绑的版本,这是 3.0 中引入的版本(参见 PEP-3105)。
The comments suggest its using 2.7.11 but I don't understand why its doing this
...因为那是您使用的 Python 版本?
from __future__ import ...
不会在您的计算机上搜索替代实现,它会使用与您正在使用的 Python 版本捆绑在一起的实现。如果您考虑一下,这是不可避免的,否则 future 导入将在未安装 3.x 的机器上失败。 其中大部分对我来说意义不大,但是:
I assumed that since it was a future statement it also brought in the print function from a future release.
这正是它正在做的。不过,您无法选择哪个 future 版本。您将获得在添加到
__future__
时计划发布的版本。-
is there not a natural way to import future python functions to my current python script?
是的,这就是您使用的方式,只要该功能在
__future__
中受支持即可。 .is it not possible to use that function
不是您正在使用的 Python 版本中的 3.3 及更高版本,不*。如果您需要较新版本的 Python 提供的功能,请使用较新版本的 Python。 2.x 已无路可走。
It was (at least to me) counter intuitive to have the parser act like future python but still act like a 2.7.11
它不像 2.7.11"那样[表演]。它使用 3.x 中的 print 函数而不是 2.x 中的 print 语句。如果您在导入
print_function
之后尝试print 'hello'
,您将像在 3.x 中一样得到一个SyntaxError
。* 假设您不打算入侵您的安装
关于python - 如何在 Python 2.7.x 中导入最新版本的打印功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39194615/