Bill Hayden Bill Hayden - 9 days ago 7
Python Question

Redirect print() to file in python 2.4

I'm backporting a modern python script to 2.4 to make it compatible with stock RHEL 5.X. While most of the work has been fairly straight-forward, I can't figure out how to handle this case where I am appending to a file:


This is a very common construct in the code I'm porting. I am using the print function from future, which works fine, but here it chokes on the "file=file("filename", 'ab')" part. Apparently this kind of redirection is not supported in 2.4. Likewise, I haven't found a way for the print function to support the >> operator from the old print. It would be an enormous task to re-write this script without the print function, so I'd like a solution based on the print function.

I've found plenty of docs showing how to use >> in the old print, or file=file() in the new print function, but nothing that actually works in 2.4.

What is the equivalent Python 2.4 compatible code for this?


The syntax is pretty awful:

print >> file('/tmp/bar', 'ab'), 'Foo'

Though of course you should rather write:

f = open('/tmp/bar', 'ab')
    print >> f, 'Foo'

to make sure that the output is actually closed and flushed. (Python 2.4 doesn't have with statement!).

As an alternative to converting everything to print statement, you could also try the print_ function from the Six: Python 2 and 3 Compatibility Library. I am not sure whether the whole library supports 2.4 any longer, but that one function should be OK in 2.4.