Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: Print thread safe

I've seen a similar post here however it refers to Python 2.6 and I was hoping there was an easier way.

From reading the thread it seems the best way is to just replace all my print statements with sys.stdout.write(s + '\n') ?

I was hoping there was a nicer way that allowed me still to use print

like image 726
Setheron Avatar asked Oct 24 '11 15:10

Setheron


People also ask

Is print in Python thread-safe?

The print() function is a built-in function for printing a string on stdout and is not thread-safe.

How do you make a Python code thread-safe?

If a class or a program has immutable state then the class is necessarily thread-safe. Similarly, the shared state in an application where the same thread mutates the state using an operation that translates into an atomic bytecode instruction can be safely read by multiple reader threads.

Are Python strings thread-safe?

Yes, they are immutable, just like strings. The code x += 1 actually creates a brand new integer object and assigns it to x . In case it's not clear, things that are immutable are automatically thread safe because there is no way for two threads to try to modify the same thing at the same time.


1 Answers

from __future__ import print_function
print = lambda x: sys.stdout.write("%s\n" % x)

Is a nice cheap and dirty hack.

like image 151
Jakob Bowyer Avatar answered Sep 27 '22 20:09

Jakob Bowyer