【发布时间】:2019-07-24 02:26:58
【问题描述】:
我使用的是 Python 3.7.4,我创建了两个函数,第一个函数使用 multiprocessing.Process 执行可调用函数,第二个函数只打印“Hello World”。在我尝试重定向标准输出之前,一切似乎都运行良好,这样做会阻止我在流程执行期间获得任何打印值。我已将示例简化到最大程度,这是我目前遇到的问题代码。
这些是我的功能:
import io
import multiprocessing
from contextlib import redirect_stdout
def call_function(func: callable):
queue = multiprocessing.Queue()
process = multiprocessing.Process(target=lambda:queue.put(func()))
process.start()
while True:
if not queue.empty():
return queue.get()
def print_hello_world():
print("Hello World")
这行得通:
call_function(print_hello_world)
前面的代码运行成功,打印出“Hello World”
这不起作用:
with redirect_stdout(io.StringIO()) as out:
call_function(print_hello_world)
print(out.getvalue())
使用前面的代码,我没有在控制台中打印任何内容。
任何建议将不胜感激。我已经能够将问题缩小到这一点,我认为这与 io.StringIO() 已经关闭后结束的过程有关,但我不知道如何检验我的假设,更不知道如何实施解决方案。
【问题讨论】:
标签: python-3.x python-multiprocessing stringio redirectstandardoutput