Skip to main content
 首页 » 编程设计

python之如何将 python 自身对象传递给另一个 python 脚本

2025年05月04日13me-sa

我有一个奇怪的要求,我需要从 python 调用一个脚本,我正在使用 subprocess 模块,然后从脚本调用原始类的函数。我有这样的东西 -

import subprocess 
import textwrap 
import sys 
class caller: 
  def call_script(self): 
     script = textwrap.dedent("""\ 
          #! /usr/bin/env python 
          import caller 
          print ("Before the callback") 
          caller().callback() 
          print ("After the callback") 
      """) 
     subprocess.Popen(script, shell=True, executable=sys.executable()) 
 
   def callback(self): 
      print("inside the callback") 

当然,现在我意识到将从脚本调用的回调不是执行脚本的同一对象的方法。有没有什么方法可以将 self 对象传递给脚本,或者有什么其他方法可以获取调用脚本的原始对象的回调方法?

请您参考如下方法:

该脚本恰好运行在一个完全不同的进程中,您必须设计一种在进程之间进行通信的方法。 (为此你可以使用:本地套接字,可能是 multiprocessing 包,可能是通过子进程的管道)- 没有简单的方法将有意义的对象引用传递到另一个进程。