Non-interfering printing from threads
Doing some threading with a python script and it spits out stuff in all kinds of orders. However, I want to print out a single "Remaining: x" at the end of each thread and then erase that line before the next print statement. So basically, I'm trying to implement a progress/status update that erases itself before the next print statement.
I have something like this:
for i in range(1,10): print "Something here" print "Remaining: x" sleep(5) sys.stdout.write("\033[F") sys.stdout.write("\033[K")
This works fine when you're printing this out just the way it is; however, as soon as you implement threading, the "Remaining" text doesn't get wiped out all the time and sometimes you get another "Something here" right before it wipes out the previous line.
Just need a bit of help trying to figure out the best way to get my progress/status text organized with multithreading.
Since your code doesn't include any threads it's difficult to give you specific advice about what you are doing wrong.
If it's output sequencing that bothers you, however, you should learn about locking, and have the threads share a lock. The idea would be to grab the lock (so nobody else can), send your output and flush the stream before releasing the lock.
However, the way the code is structured makes this difficult, since there is no way to guarantee that the cursor will always end up at a specific position when you have multiple threads writing output.
As previous commenter mentioned, you can use mutex (RLock) object to serialize access.
import threading # global lock stdout_lock = threading.RLock() def log_stdout(*args): global stdout_lock msg = "" for i in args: msg += i with stdout_lock: sys.stdout.write(msg) for i in range(1,10): log_stdout("Something here\n") log_stdout("Remaining: x\n") sleep(5) log_stdout("\033[F") log_stdout("\033[K")