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

如何让Python多进程中子进程调用父进程的函数?

让子进程触发父进程执行函数的Python实现

我在编写Python程序时,需要通过multiprocessing模块启动的子进程,触发父进程执行指定函数。

先看一段基础示例代码,它会先后在父进程和子进程中调用child_or_parent()函数:

#!/usr/bin/env python3
import multiprocessing, os

# 保存主(父)进程的PID
parent_pid = os.getpid()

# 判断当前运行环境是父进程还是子进程的函数
def child_or_parent():
    if os.getpid() == parent_pid:
        print( "I am the parent process" )
    else:
        print( "I am a child process" )

# 父进程调用函数
child_or_parent() 

# 子进程调用函数
child = multiprocessing.Process( target=child_or_parent )
child.start()

执行后输出:

I am the parent process
I am a child process

我的需求是修改程序,让子进程触发父进程上下文执行child_or_parent(),最终输出"I am the parent process"。下面这段代码中的child_call_parent()包含无效的伪代码,需要替换为可实现需求的逻辑:

#!/usr/bin/env python3
import multiprocessing, os

# 保存主(父)进程的PID
parent_pid = os.getpid()

# 判断当前运行环境是父进程还是子进程的函数
def child_or_parent():
    if os.getpid() == parent_pid:
        print( "I am the parent process" )
    else:
        print( "I am a child process" )

def child_call_parent():

    # FIXME 这段代码无效!
    self.parent.child_or_parent()

# 让子进程调用父进程里的函数
child = multiprocessing.Process( target=child_call_parent )
child.start()

实现方案

Python多进程拥有独立内存空间,子进程无法直接调用父进程的函数,必须通过**进程间通信(IPC)**传递指令,让父进程自行执行目标函数。以下是基于multiprocessing.Queue的实现方式:

完整可运行代码

#!/usr/bin/env python3
import multiprocessing, os

# 保存主(父)进程的PID
parent_pid = os.getpid()

# 判断当前运行环境是父进程还是子进程的函数
def child_or_parent():
    if os.getpid() == parent_pid:
        print( "I am the parent process" )
    else:
        print( "I am a child process" )

def child_call_parent(ipc_queue):
    # 子进程向队列发送执行指令
    ipc_queue.put("execute_target")

def parent_listener(ipc_queue):
    # 父进程监听队列,收到指令则执行目标函数
    msg = ipc_queue.get()
    if msg == "execute_target":
        child_or_parent()

if __name__ == "__main__":
    # 创建进程间通信队列
    ipc_queue = multiprocessing.Queue()

    # 启动父进程的监听进程
    listener_proc = multiprocessing.Process(target=parent_listener, args=(ipc_queue,))
    listener_proc.start()

    # 启动子进程,传递通信队列
    child_proc = multiprocessing.Process(target=child_call_parent, args=(ipc_queue,))
    child_proc.start()

    # 等待子进程和监听进程执行完毕
    child_proc.join()
    listener_proc.join()

逻辑说明

  1. IPC队列:ipc_queue作为父子进程的通信桥梁,子进程通过它发送执行信号。
  2. 父进程监听:parent_listener函数负责监听队列,一旦收到指定指令,就调用child_or_parent()——此时函数运行在父进程上下文,因此会输出I am the parent process。
  3. 子进程触发:child_call_parent仅需向队列发送指令,无需关心函数执行细节。

执行上述代码后,输出为:

I am the parent process

内容的提问来源于stack exchange,提问作者Michael Altfield

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:49:56