Redirect print () to a file in python 2.4

I am loading a modern python script in 2.4 to make it compatible with RHEL 5.X stock. Although most of the work was pretty straightforward, I cannot figure out how to handle this case when I add a file:

print("Foo",file=file("/tmp/bar",'ab'))

This is a very common construct in the code that I port. I use a print function from the future that works fine, but here it suffocates in the "file = file (" filename "," ab ")" part. Apparently this kind of redirection is not supported in 2.4. Similarly, I did not find a way for the print function to support the → operator from old print. It would be a huge task to rewrite this script without a print function, so I would like to get a solution based on a print function. A.

I found many documents showing how to use → in old print, or file = file () in the new print function, but nothing works in 2.4.

What is the equivalent code for Python 2.4 for this?

+4
source share
1 answer

The syntax is pretty terrible:

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

Although, of course, it is better to write:

f = open('/tmp/bar', 'ab')
try:
    print >> f, 'Foo'
finally:
    f.close()

to ensure that the output is actually closed and reset. (Python 2.4 has no operator with!).


As an alternative to converting everything to an operator, printyou can also try the print_function from Six: Python 2 and 3 compatibility library . I'm not sure the whole library supports 2.4 anymore, but this function should be ok 2.4.

+4
source

Source: https://habr.com/ru/post/1652384/


All Articles