【发布时间】:2015-08-14 10:33:42
【问题描述】:
我正在尝试从 Python Process 对象内部读取 sys.stdin,但我不断收到“ValueError: I/O operation on closed file”结果。这是一个简单的例子:
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
上面的脚本总是失败:
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
当然,只需调用do_something(input) 就可以在不使用进程的情况下正常工作。创建一个Pipe() 对象似乎有帮助——我可以将标准输入的内容写入管道并从进程中以字符串形式获取结果——但我实际上需要以类似文件的形式输入一些下游操作。我可以将内容转储到一个文件中,然后从进程中重新读取它,但这看起来很笨拙,尤其是在标准输入非常大的情况下。是否有一些简单的方法可以从进程中读取 sys.stdin?
【问题讨论】: