0

I need an input() in a process for my application. I wrote a small test because I have experienced some problems with it.

from multiprocessing import Process, Queue

class InputCatcher(Process):
    def __init__(self, input_queue):
        Process.__init__(self)
        self.input_queue = input_queue

    def run(self):
        while True:
            self.input_queue.put(input())


input_queue = Queue()
ic = InputCatcher(input_queue)
ic.daemon = True
ic.start()

while True:
    if not input_queue.empty():
        print(input_queue.get())

Unfortunately I get this error:

Process InputCatcher-1:
Traceback (most recent call last):
File "/usr/lib/python3.3/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/****/PycharmProjects/****/test/inputtestproces.py", line 13, in run
self.input_queue.put(input())
EOFError: EOF when reading a line

Is there a way to get this to work?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
w5e
  • 199
  • 1
  • 12

1 Answers1

3

From the multiprocessing docs (https://docs.python.org/2/library/multiprocessing.html#all-platforms):

multiprocessing originally unconditionally called:

os.close(sys.stdin.fileno())

in the multiprocessing.Process._bootstrap() method — this resulted in issues with processes-in-processes. This has been changed to:

sys.stdin.close()

sys.stdin = open(os.devnull)

So forking a process closes stdin for that process and replaces it with a file descriptor for /dev/null.

In answer to your question, a way around this is to reverse the logic of your code and have the main process wait on user input while the forked process does the original job of the main.

As and aside: From the code that you have posted, it looks like you might be better of using the threading module than the multiprocessing module. Unless you are planning on doing some compute intensive stuff in the forked processes, the multiprocessing module is a bit like overkill. Also inter-thread communication is usually simpler than inter-process communication.

ebarr
  • 7,704
  • 1
  • 29
  • 40
  • The reason the OP is using multiprocessing instead of threading is because [`input` blocks the whole process](http://stackoverflow.com/questions/23081060/input-is-blocking-the-use-of-processes). My answer there recommended putting the input loop in a subprocess (instead of a thread in the OPs original code). I've since updated it to not be so inadvertently misleading. – lvc Apr 15 '14 at 13:27