I’ve got a system that needs to receive input from a few different processes. The simplest is just a command line where the user enters data manually. This data will be added to a multiprocessing.Queue and handled later by the main process, but I’m not even getting that far; calling raw_input inside a process doesn’t seem to work. I pulled out the meat of the code and here’s an example:
import multiprocessing
def f():
while True:
raw_input('>>>')
p = multiprocessing.Process(target = f)
p.start()
This simple code throws this:
~$ python test.py
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap
self.run()
File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "test.py", line 5, in f
raw_input('>>>')
EOFError: EOF when reading a line
>>>~$
How can I get command line input in a process in Python?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
When you spawn a thread in Python, it closes stdin. You can’t use a subprocess to collect standard input. Use the main thread to collect input instead and post them to the Queue from the main thread. It may be possible to pass the stdin to another thread, but you likely need to close it in your main thread.
Method 2
I was able to work around this by using fdopen() to reopen stdin in the subprocess. See this answer. It seems to be working, I don’t know if there are any hidden risks.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0