【问题标题】:Why is there SyntaxError to this equal sign when printing to a file?为什么打印到文件时这个等号会出现 SyntaxError?
【发布时间】:2015-04-25 03:09:55
【问题描述】:

我在 macbook 上使用终端将数据打印到打开的文件中:

>>> out=open("test_output.txt","w")
>>> print("hello",file=out)
  File "<stdin>", line 1
    print("hello",file=out)
                      ^
SyntaxError: invalid syntax

为什么会有 SyntaxError 以及如何修复它?无论如何,相同的脚本在 IDLE 中运行良好。

PS:

它是 Python 2.7,我实际上已经安装了 Python 3.5,但是 NetworkX 和 Matplotlib 的包都自动安装到 Python 2.7 的库中,所以这是我在进行社交网络分析时使用的平台。

【问题讨论】:

  • 这是 python 2 还是 3?
  • 您实际上在尝试什么 print ?您是否尝试打印文件对象?
  • print() 函数是 Python 3 的一个特性;如果文件以 from __future__ import print_function 开头,它也可以在 Python 2.6+ 中使用(通常推荐)
  • @Antti - 次要澄清:您可以使用至少可以追溯到 Python 2.5 的 print() 语法,但它只更改为 act 就像 3 中的一个函数,以及从 2.6 开始的 __future__ 模块。就像你说的那样。
  • 这是 python 2.7,感谢 Antti,它可以工作了!!

标签: python printing terminal


【解决方案1】:

在我开始回答你关于语法错误的问题之前,我首先需要告诉你 Python 有 两个 版本。 Python 2 和 Python 3。Python 3 是该语言的假定未来,也是在您的 IDLE 安装中运行的版本。 Python 2 是您在命令行中调用 python 时使用的版本。

两者之间没有太大区别,但print 肯定是其中之一。 print 在 Python 3 中是一个 function,但在 Python 2 中是一个 statement。这意味着什么?在 Python 2 中, print 不返回任何内容,它只是将数据推送到命令行中。在 Python 3 中,它实际上 返回 一些东西。这意味着在 Python 3 中,您可以执行以下操作:

a = print("thing")

在python 2中,如果我们做同样的事情,我们会得到一个语法错误:

>>> a = print("thing")
  File "<input>", line 1
    a = print("thing")
            ^
SyntaxError: invalid syntax

因为print 是 Python 3 中的函数,您可以为其提供额外的参数。这就是为什么你可以做类似print("thing", out=file) 的事情。在 python 2 中,等价于 print&gt;&gt;file, "thing"

所以,您现在有几个选择。您可以更改 .py 文件以反映 Python 2 中的正确语法。您可以使用 python 3 而不是 python 2 运行文件,使用 python3 在命令行中调用 python。

【讨论】:

    【解决方案2】:

    如果您希望上述代码在 python-2(2.6 及更高版本)中可移植,则需要从 future module 导入 print_function

    例子:

    from __future__ import print_function
    out=open("test_output.txt","w")
    print("hello",file=out)
    

    article 列出了 python-2.X 中 print 语句的用法与 python-3.x 中 print 函数的区别。

    【讨论】:

      【解决方案3】:

      如果你使用终端来做

      $ python filename.py
      

      我几乎保证您实际上是在 Python2 中运行 Python3 代码 (print(...))。尝试改为:

      $ py -3 filename.py
      

      看看这是否不能解决您的问题。

      要确认,你可以这样做:

      $ python --version
      

      【讨论】:

        猜你喜欢
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        • 2014-08-23
        • 1970-01-01
        • 2020-05-19
        • 1970-01-01
        相关资源
        最近更新 更多