如何在Jupyter Notebook中并行运行两个单元格的独立进程?
Jupyter Notebook多单元格并行进程独立输出方案
完全可以实现你的需求,下面是亲测可行的具体方案,核心是让每个单元格的子进程通过队列传递输出,当前单元格主进程监听队列并打印,实现各自独立输出:
1. 先定义通用任务函数
在单独的一个单元格里定义你要运行的函数,把输出内容通过队列传递(不能直接用print,子进程的默认输出不会显示在单元格里):
import time def run_task(input_param, output_queue): # 模拟耗时计算过程,每一步发送日志到队列 for step in range(1, 6): log_msg = f"{input_param} 正在执行第 {step} 步..." output_queue.put(("log", log_msg)) time.sleep(1) # 任务完成后发送最终结果 final_result = f"{input_param} 计算完成!结果:{input_param.upper()}" output_queue.put(("result", final_result))
2. 单元格1:运行Input A
在第一个单元格里启动子进程,监听队列并实时输出内容:
import multiprocessing from multiprocessing import Queue import time # 创建队列用于接收子进程的输出消息 queue_a = Queue() # 启动子进程,传入Input A和队列 process_a = multiprocessing.Process( target=run_task, args=("Input A", queue_a) ) process_a.start() # 循环监听队列,把内容打印到当前单元格 while process_a.is_alive() or not queue_a.empty(): if not queue_a.empty(): msg_type, content = queue_a.get() if msg_type == "log": print(content) elif msg_type == "result": print(f"\n{content}") time.sleep(0.1) # 等待进程结束 process_a.join()
3. 单元格2:运行Input B
第二个单元格的代码和第一个几乎一样,只需要替换参数为Input B:
import multiprocessing from multiprocessing import Queue import time queue_b = Queue() process_b = multiprocessing.Process( target=run_task, args=("Input B", queue_b) ) process_b.start() while process_b.is_alive() or not queue_b.empty(): if not queue_b.empty(): msg_type, content = queue_b.get() if msg_type == "log": print(content) elif msg_type == "result": print(f"\n{content}") time.sleep(0.1) process_b.join()
关键说明
- 运行顺序:先执行定义函数的单元格,然后依次运行单元格1和单元格2(间隔别太长,确保两个进程并行)
- IO密集型任务优化:如果你的任务是IO密集型(比如网络请求),可以用
threading.Thread替代multiprocessing.Process,代码逻辑完全一致,资源开销更小 - 为什么不用直接
print:Jupyter的子进程stdout默认绑定到内核控制台,不会显示在单元格里,所以必须通过队列传递输出内容 - 进程安全:队列是进程安全的,不用担心多进程读写冲突
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

