Syntax error when using “with open” in Python (python newbie)

点点圈 提交于 2020-01-11 04:33:04

问题


[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

The code looks like this:

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

and I am using Python 2.5.5

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

回答1:


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

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:

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

#!/usr/bin/python2.5

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

#!/usr/bin/env python2.5



回答2:


Maybe like this?

#!/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")



回答3:


the answer to this question is buried in the comments of the OP. @Tamas gave the correct solution above once @Tony confirmed that his code was being executed by 2.4:

"So, /usr/local/bin/python is 2.5.5, but you are calling your script with /usr/bin/python which is 2.4.3. Try replacing the shell shebang line with this: #!/usr/bin/env python."

in general, be wary of hardcoding your path, i.e., /usr/bin, /usr/local/bin, etc. this is why the env command was invented. it's especially relevant when you have multiple versions of Python installed on your system.

however, it was a pretty clear giveaway that it was an old Python issue as that OP code will execute on any 2.5 and newer interpreter. that syntax error gives off this message regardless of what version of Python you think you're using.



来源:https://stackoverflow.com/questions/2685097/syntax-error-when-using-with-open-in-python-python-newbie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!