Python using STDIN in child Process

后端 未结 4 878
终归单人心
终归单人心 2020-12-11 18:29

So I have a program, in the \"main\" process I fire off a new Process object which (what I want) is to read lines from STDIN and append them to a Queue object.

Ess

4条回答
  •  遥遥无期
    2020-12-11 19:09

    You could use threading and keep it all on the same process:

    from multiprocessing import Queue
    from Queue import Empty
    from threading import Thread
    
    def sub_proc(q):
        some_str = ""
        while True:
            some_str = raw_input("> ")
            if some_str.lower() == "quit":
                return
            q.put_nowait(some_str)
    
    if __name__ == "__main__":
        q = Queue()
        qproc = Thread(target=sub_proc, args=(q,))
        qproc.start()
        qproc.join()
    
        while True:
            try:
                print q.get(False)
            except Empty:
                break
    

提交回复
热议问题