0

I have multiple python threads printing output to a command line window. Each process writes logging messages to the command line window. Depending on the timing of the print operations, it sometimes happens that two lines (from different processes) are printed on a single line:

time1:Output_process_1time2:Output_process_2

Is there any way of guaranteeing every line is printed on a different line in the command window, as such

 Time1:Output_process_1
 Time2:Output_process_2

I've played around with adding breakline characters. But this only makes empty lines appear.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ElenorDavey
  • 247
  • 1
  • 2
  • 7
  • 1
    [Keynote on Concurrency, PyBay 2017](https://www.youtube.com/watch?v=9zinZmE3Ogk) is a good watch, it even has an example demonstrating the problem you are having. One way to fix it might be to have another thread that just prints what it is *fed* then all the other threads feed it but don't print. – wwii Mar 29 '18 at 18:51
  • 1
    Use a [lock](https://docs.python.org/3/library/threading.html#lock-objects)? – t.m.adam Mar 29 '18 at 20:07
  • 1
    The best approach for this should be (as wwii wrote) using a designated thread for logging and a queue. Each thread push its log message to the queue and the logging thread print them one by one. – Nir Apr 01 '18 at 11:55

1 Answers1

0

The answers given above are good suggestions. I also found another solution on stack overflow after some more searching:

How to share stdout for multi-threaded python script?

This answer suggest to use the logging module for python, which is supposed to be thread safe.

ElenorDavey
  • 247
  • 1
  • 2
  • 7