views:

248

answers:

3
[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
+3  A: 

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
Benson
yes I do have multiple versions, and that worked. i am using this for a git post commit hook so i think it wants to do "./test.py"
Tony
might want to edit your answer to mention that this can be fixed by changing the shebang line to point to the correct version of python. thanks!
Tony
Good point. I've edited my post to add that; thanks for pointing it out.
Benson
+1  A: 

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")
Krumelur
A: 

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.

wescpy