Skip to main content
 首页 » 编程设计

python之在 Python 中将进程作为子进程启动

2025年05月04日16落叶

我正在使用以下代码编写一个使用多个工作进程(预 fork 模型)的程序。

from  multiprocessing import Process 
for i in range(0,3): 
    Process(target=worker, args=(i,)).start() 

我使用 Windows。当我希望它们作为 子进程 启动时,我注意到它们作为单独的进程运行。如何使它们成为主流程的子流程?

我对使用 subprocess 模块犹豫不决,因为它似乎适合运行外部进程(就我使用过的而言)。


更新:Windows 似乎不会将新进程作为子进程启动。 Python 不支持 Windows 中的 getppid()(获取父级的 PID)。

请您参考如下方法:

你的子进程是什么?对我来说,它们是您主要流程的子流程。这是我的示例和返回的输出。

import time, os 
from  multiprocessing import Process 
 
def worker(): 
    print "I'm process %s, my father is %s" % (os.getpid(), os.getppid()) 
 
print "I'm the main process %s" % os.getpid() 
for i in range(0,3): 
    Process(target=worker).start() 

输出是:

I'm the main process 5897 
I'm process 5898, my father is 5897 
I'm process 5899, my father is 5897 
I'm process 5900, my father is 5897 

您有 3 个子流程附加到一个主流程...