You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多进程代码无输出问题排查:为何得不到预期打印结果?

解决multiprocessing代码无输出的问题

我看了你的multiprocessing代码,运行后没输出大概率是子进程的输出缓冲导致的,尤其是在Windows系统下(Windows的multiprocessing用spawn方式启动子进程,和Unix的fork机制不同)。

你原来的代码里,print语句的输出会被系统缓冲,子进程结束前可能没把缓冲内容刷到控制台,所以你看不到任何输出。

解决方法很简单,给print函数加上flush=True参数,强制刷新输出缓冲:

from multiprocessing import Process
def print_func(continent = 'Asia'):
    print('The name of continent is: ', continent, flush=True)  # 添加flush=True强制刷新
if __name__ == "__main__":
    names = ['America','Russia','Africa']
    procs = []
    proc = Process(target = print_func)
    procs.append(proc)
    proc.start()
    for name in names:
        proc = Process(target = print_func, args=(name,))
        procs.append(proc)
        proc.start()
    for proc in procs:
        proc.join()

如果是在某些IDE中运行,也可以检查下IDE设置,确保子进程的输出能被正确捕获,但优先试试上面的flush=True方案,这是最直接有效的修改。

修改后运行,就能得到你期望的输出:

The name of continent is: Asia
The name of continent is: America
The name of continent is: Russia
The name of continent is: Africa

内容的提问来源于stack exchange,提问作者Chidananda Nayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:26:40