Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将python自身对象传递给另一个python脚本_Python_Callback - Fatal编程技术网

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

如何将python自身对象传递给另一个python脚本,python,callback,Python,Callback,我有一个奇怪的需求,在这个需求中,我需要从python调用一个脚本,我正在使用子流程模块进行此操作,然后从脚本调用原始类的函数。我有这样的东西- import subprocess import textwrap import sys class caller: def call_script(self): script = textwrap.dedent("""\ #! /usr/bin/env python import caller

我有一个奇怪的需求,在这个需求中,我需要从python调用一个脚本,我正在使用子流程模块进行此操作,然后从脚本调用原始类的函数。我有这样的东西-

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对象传递给脚本,或者有任何其他方法可以获取调用脚本的原始对象的回调方法?

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

好的,正如@knitti建议的,脚本在完全不同的进程中运行,因此我通过信号、文件和全局变量的组合解决了这个问题。不是说这是最优雅的解决方案,但它对我很有效-

import subprocess, textwrap, os, signal
caller_object = None
def signal_handler(signum, frame):
   caller_object.callback()

comm_file = "/tmp/somefile"

class caller:
   def call_script(self):
     signal.signal(signal.SIGALRM, mockproc_callback)
     # Need to pass the process id to the script.
     with open(comm_file, 'w') as pipe:
        pipe.write("{0}".format(os.getpid()))

     # Also set the global object so that callback function could be called by handler
      global caller_object
      caller_object = self

     script = textwrap.dedent("""\
          #! /usr/bin/env python
          import caller, signal, os
          with open("{0}", "r") as pipe:
          # Read the pid of original process
          pid = pipe.read()
          print ("Before the callback")

          # Although its named kill, os.kill could be used to send all sort of signals to a process
          os.kill(int(pid), signal.SIGALRM)
          print ("After the callback")
      """.format(comm_file))
     subprocess.Popen(script, shell=True, executable=sys.executable())

   def callback(self):
      print("inside the callback")

我相信还有很多改进的余地。

听起来你已经自掘坟墓了。。