Hig*_*ler 3 python interprocess inter-process-communicat
我的主脚本正在运行
class Blah():
update=0
def testthings(function):
return function(9)
main = Blah()
while True:
main.update+=1
Run Code Online (Sandbox Code Playgroud)
在主脚本运行时,如何运行独立脚本以访问"主变量"(在我的主脚本中定义)?
像这样的东西会很有用
main = GetMain()
while True:
main.testthings(lambda x: x)
Run Code Online (Sandbox Code Playgroud)
使用rpyc.它干净,直观,功能强大.
基本上,你编写一个服务类来公开你想要的任何接口(例如,它有一个返回你需要的全局变量的方法),创建一个与该服务相关的服务器对象,并启动它.然后,在客户端中,使用客户端对象进行连接,并调用该函数,该函数从服务器进程返回变量.
编辑:用于运行rpyc服务器和连接rpyc客户端的代码示例
rpyc_main.py
# main definitions
import time
class Blah():
update=0
def testthings(self, function):
return function(9)
# rpyc servic definition
import rpyc
class MyService(rpyc.Service):
def exposed_testthings(self, function = lambda x: x):
return main.testthings(function = function)
def exposed_get_main_update(self):
return main.update
# start the rpyc server
from rpyc.utils.server import ThreadedServer
from threading import Thread
server = ThreadedServer(MyService, port = 12345)
t = Thread(target = server.start)
t.daemon = True
t.start()
# the main logic
main = Blah()
while True:
main.update+=1
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
rpyc_client.py
# rpyc client
import rpyc
conn = rpyc.connect("localhost", 12345)
c = conn.root
# do stuff over rpyc
import time
print 'update =', c.get_main_update()
time.sleep(2)
print 'update =', c.get_main_update()
print 'testing returned:', c.testthings(lambda x: x) # calling a method of the remote service
print 'update =', c.get_main_update()
Run Code Online (Sandbox Code Playgroud)
产量
update= 6
update= 8
testing returned: 9
update= 8
Run Code Online (Sandbox Code Playgroud)
笔记:
lambda对象(实际上是对该对象的rpyc引用)从客户端传递到服务器.当它被调用时,它实际上在客户端进程中运行.这非常酷,远非琐碎.它的工作原理是因为rpyc是对称的