I'm trying to read from sys.stdin from inside of a Python Process object, but I keep getting a "ValueError: I/O operation on closed file" result. Here's a quick example:
import sys
from multiprocessing import Process
def do_something(input_data):
for x in input_data:
print x
input=sys.stdin
p = Process(target=do_something, args=(input,))
p.start()
p.join() #Wait for Process to complete
The above script always fails with:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "example.py", line 6, in do_something
for x in input_data:
ValueError: I/O operation on closed file
Just calling do_something(input)
works fine without using a Process, of course. Creating a Pipe()
object seems to help - I can write the contents of stdin to the Pipe and get the results in string form from within the process - but I actually need the input to file-like form for some downstream operations. I could dump the contents to a file and the re-read it in from within the Process, but that seems pretty clumsy, especially if the stdin is really big. Is there some easy way to read from sys.stdin from within a Process?