为什么使用 from __future__ import print_function 会破坏 Python2 风格的打印?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32032697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does using from __future__ import print_function breaks Python2-style print?
提问by UHMIS
I am new at programming with python, and I am trying to print out with a separator and end but it is still giving me a syntax error.
我是用 python 编程的新手,我试图用分隔符和结尾打印出来,但它仍然给我一个语法错误。
I am using python 2.7.
我正在使用 python 2.7。
Here is my code:
这是我的代码:
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print x, sep=' ', end=''
time.sleep(1)
And here is the error:
这是错误:
$ python2 xy.py
File "xy.py", line 5
print x, sep=' ', end=''
^
SyntaxError: invalid syntax
$
采纳答案by Cyphase
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
functionfrom Python 3 into Python 2.6+.
首先,from __future__ import print_function
需要是脚本中的第一行代码(除了下面提到的一些例外)。其次,正如其他答案所说,您现在必须将其print
用作函数。这就是重点from __future__ import print_function
;将print
函数从 Python 3 引入 Python 2.6+。
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
__future__
语句需要靠近文件的顶部,因为它们改变了语言的基本内容,因此编译器需要从一开始就知道它们。从文档:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
在编译时识别并特殊处理 future 语句:对核心构造语义的更改通常通过生成不同的代码来实现。甚至可能出现新功能引入新的不兼容语法(例如新的保留字)的情况,在这种情况下,编译器可能需要以不同方式解析模块。这样的决定不能推迟到运行时。
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
该文档还提到,可以在__future__
语句之前的唯一内容是模块文档字符串、注释、空行和其他未来语句。