catch output of threads

Robin Munn rmunn at pobox.com
Sat Nov 30 13:04:06 EST 2002


William <wilk-spamout at flibuste.net> wrote:
> martin at v.loewis.de (Martin v. Löwis) writes:
> 
>> William <wilk-spamout at flibuste.net> writes:
>> 
>> > Is it possible to catch the output from print of differents threads ?
>> > In a single thread, i can change the value of sys.stdout... but with
>> > differents thread i don't know ?
>> 
>> You can still change the value of sys.stdout, even for multiple
>> threads. The print statement internally uses sys.stdout itself.
>> 
>> If multiple threads interleave print statements, you will get mixed
>> output on your replaced sys.stdout, just as you would with the
>> standard sys.stdout.
> 
> It's why i cannot use this method... I specialy want to catch the output
> to don't mix the ouput from all the threads.

In that case, you probably want to use locking to guarantee that one
thread's output won't get mixed with another. I don't know, off the top
of my head, exactly what the locking interface is -- read the docs for
the threading module. But what you'll want is something like:

    output_lock = Lock()
    # Some non-output code...
    output_lock.acquire()
    print "Here is some output"
    print "This will not be mixed"
    output_lock.release()

That should be what you want -- as long as all your threads acquire the
lock before they print, and release the lock when they're done, your
threads' outputs will not be mixed.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



More information about the Python-list mailing list