Tuesday 8 January 2013

Synchronized print in Python

Today I faced a problem where I had to print to the standard output in a synchronized way. I put the following code in a file named rpython.py
from __future__ import print_function
from threading import Lock

_global_lock = Lock()
_old_print = print 

def print(*a, **b):
        with _global_lock:
                _old_print(*a, **b)
Now, in every Python module that requires synchronized printing I typed:
from __future__ import print_function
from rpython import print
Alternatively, if you don't want to shadow the default printing you can type:
from __future__ import print_function
from rpython import print as rprint
Have a nice, synchronized day.
EDIT: I should have started with a clear statement that Python's print is not synchronized in any way. Multiple threads writing concurrently to any stream can interfere and usually they do that, so as an effect you get a random mixture of massages which looks really ugly.

1 comment:

  1. It is really a great post by you.
    Making task is one of the pieces of a professional education that gives a superior comprehension of the subject to the understudy. The greater part of the understudies stuck while making their task. Are you additionally one of them. In the event that indeed, there are numerous task creators in market who will give assistance you in making your tasks and assist you with achieving passing marks.
    A wide range of subjects where understudies generally look for online task help are SITXFIN003 assessment answers Help, Management Assignment Help, bsbdiv501 appraisal replies, and so on.

    importance of a balanced diet

    ReplyDelete