在Python中使用"with open"时出现语法错误(python newbie)

Ton*_*ony 13 python syntax-error

[root@234571-app2 git]# ./test.py 
  File "./test.py", line 4
    with open("/home/git/post-receive-email.log",'a') as log_file:
            ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

代码如下所示:

[root@234571-app2 git]# more test.py 
#!/usr/bin/python
from __future__ import with_statement

with open("/home/git/post-receive-email.log",'a') as log_file:
    log_file.write("hello world")
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 2.5.5

[root@234571-app2 git]# python -V
Python 2.5.5
Run Code Online (Sandbox Code Playgroud)

Ben*_*son 8

你有什么应该是正确的.Python 2.5引入了with语句作为可以从中导入的内容__future__.由于你的代码是正确的,我能想到的唯一解释是你的python版本不是你想象的那样.您很有可能在系统上安装了多个版本的python,并且出于某种原因,您的代码使用旧版本运行.尝试像这样运行:

[root@234571-app2 git]# /usr/bin/python2.5 test.py
Run Code Online (Sandbox Code Playgroud)

假设这有效,您可以更改第一行以指示您想要的python版本.这可以是直接路径,python2.5也可以使用env命令搜索PATHpython2.5 的用户变量.正确的方法取决于您的系统python安装是什么.以下是两种方法:

要直接使用/usr/bin/python2.5,您可以这样做:

#!/usr/bin/python2.5
Run Code Online (Sandbox Code Playgroud)

要使用PATH中首先出现的python2.5版本,请执行以下操作:

#!/usr/bin/env python2.5
Run Code Online (Sandbox Code Playgroud)


Kru*_*lur 5

也许像这样?

#!/usr/bin/env python2.5
from __future__ import with_statement

with open("/home/git/post-receive-email.log",'a') as log_file:
    log_file.write("hello world")
Run Code Online (Sandbox Code Playgroud)