Question

I have the following python code, its working fine with python 2.7, but I want to run it on python 2.5.

I am new to Python, I tried to change the script multiple times, but i always I got syntax error. The code below throws a SyntaxError: Invalid syntax:

#!/usr/bin/env python

import sys
import re
file = sys.argv[1]
exp = sys.argv[2]

print file
print exp
with open (file, "r") as myfile:

    data=myfile.read()

    p = re.compile(exp)
    matches = p.findall(data)
    for match in matches:
        print " ".join("{0:02x}".format(ord(c)) for c in match)
Was it helpful?

Solution 2

Python 2.5 does not have the with code block support.

Do this instead:

myfile = open(file, "r")
try:
    data = myfile.read()
    p = re.compile(exp)
    matches = p.findall(data)
    for match in matches:
        print " ".join("{0:02x}".format(ord(c)) for c in match)
finally:
    myfile.close()

note: you should not use file as the name of your file, it is an internal Python name, and it shadows the built in.

OTHER TIPS

Python 2.5 doesn't support the with statement yet.

To use it in Python 2.5, you'll have to import it from __future__:

## This shall be at the very top of your script ##
from __future__ import with_statement

Or, as in the previous versions, you can do the procedure manually:

myfile = open(file)
try:
    data = myfile.read()
    #some other things
finally:
    myfile.close()

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top