Alex Rivera | Logout

How do I get a thread safe print in Python 2.6?

Asked 2010-06-12T19:15:43.393
56

print in Python is not thread safe according to these articles.

A Python 3 work-around is offered in the latter article.

How do I get a thread safe print in Python 2.6?

Edit
Report

1 Answer

13

I dont know if there is any better way instead this locking mechanism, but atleast it looks easy. I am also not sure if printing really isnt thread safe.

Edit: Okay tested it my self now, you are right, you can get really wierd looking output. And you dont need the future import, its just there, because i use Python 2.7.

from __future__ import print_function
from threading import Lock

print_lock = Lock()
def save_print(*args, **kwargs):
  with print_lock:
    print (*args, **kwargs)

save_print("test", "omg", sep='lol')
answered 2010-06-12T19:26:36.857

Your Answer