使用“with open"时出现语法错误在 Python 中(python 新手) [英] Syntax error when using "with open" in Python (python newbie)

查看:50
本文介绍了使用“with open"时出现语法错误在 Python 中(python 新手)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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

代码如下:

[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")

我使用的是 Python 2.5.5

and I am using Python 2.5.5

[root@234571-app2 git]# python -V
Python 2.5.5

推荐答案

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

What you have should be correct. Python 2.5 introduced the with statement as something you can import from __future__. Since your code is correct, the only explanation I can think of is that your python version is not what you think it is. There's a good chance you have multiple versions of python installed on the system and for some reason your code is running with an older version. Try running it like this:

[root@234571-app2 git]# /usr/bin/python2.5 test.py

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

Assuming this works, you can change your first line to indicate which version of python you'd like. That can either be a direct path to python2.5 or you can use the env command to search the user's PATH variable for python2.5. The correct approach depends on what your systems python installs are. Here are the 2 approaches:

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

To use /usr/bin/python2.5 directly, you can do this:

#!/usr/bin/python2.5

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

To use whichever version of python2.5 occurs first in your PATH, do this:

#!/usr/bin/env python2.5

这篇关于使用“with open"时出现语法错误在 Python 中(python 新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆