问题:为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

我是使用python编程的新手,但我尝试使用分隔符并结束打印,但这仍然给我带来语法错误。

我正在使用python 2.7。

这是我的代码:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

这是错误:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

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.

I am using 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
$

回答 0

首先,from __future__ import print_function必须是脚本中的第一行代码(除了下面提到的一些exceptions)。第二,正如其他答案所说,您现在必须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__语句必须位于文件的顶部,因为它们会更改语言的基本内容,因此编译器需要从一开始就了解它们。从文档中

将来的语句在编译时会得到特殊识别和处理:更改核心结构的语义通常是通过生成不同的代码来实现的。甚至可能是新功能引入了新的不兼容语法(例如新的保留字)的情况,在这种情况下,编译器可能需要以不同的方式解析模块。直到运行时才能推迟此类决策。

该文档还提到,__future__语句之前唯一可以做的事情就是模块文档字符串,注释,空白行和其他将来的语句。

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 function from Python 3 into 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:

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.

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。