我有一个奇怪的要求,我需要使用子进程模块从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")
我相信还有很多改进的余地。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句