Search code examples
pythonmultiprocessingcurses

Bad output when child processes writes into curses window in Python


I need your advice. I have to make a python program which will have a user interface programmed with curses module and several child precesses should be writing into one window created by curses I have this code:

#!/bin/python3

import multiprocessing
import curses
import time


class GUI:

    def __init__(self):
        self.lock = multiprocessing.Lock()
        self.window = curses.initscr()
        self.window.erase()
        self.window.refresh()

    def worker(self, i, msg):
        self.lock.acquire()
        try:
            self.window.addstr(i, 0, msg + "\n")
            self.window.refresh()
        finally:
            self.lock.release()

    def work_hub(self):

        jobs = []
        for i in range(5):
            child = multiprocessing.Process(target=self.worker, args=(i, "Worker" + str(i)))
            jobs.append(child)
            child.start()

        for job in jobs:
            job.join()

        time.sleep(5)
        curses.endwin()


if __name__ == "__main__":

    displayer = GUI()
    displayer.work_hub()

But this is how my output look like:

Worker0

Worker1


Worker2



Worker3




Worker4

And I need this output:

Worker0
Worker1
Worker2
Worker3
Worker4

Please help me. I tried almost everything what I know. Thank you.


Solution

  • It doesn't work as expected because multiprocessing creates separate subprocesses which do not know where on the screen the other subprocesses left the cursor. You could work around that by moving the cursor after the message to the same location in each subprocess (doing an extra refresh). Something like this in the worker function:

          self.window.addstr(i, 0, msg)
          self.window.refresh()
          self.window.move(10, 0)
          self.window.refresh()