4

当我的主脚本正在运行时

class Blah():
    update=0

    def testthings(function):
        return function(9)

main = Blah()
while True:
    main.update+=1

如何在主脚本运行时运行独立脚本以访问“主变量”(在我的主脚本中定义)?

像这样的东西会很有用

main = GetMain()
while True:
    main.testthings(lambda x: x)
4

1 回答 1

9

使用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)

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()

输出

update= 6
update= 8
testing returned: 9
update= 8

笔记:

  1. 一个lambda对象(实际上是对该对象的 rpyc 引用)从客户端传递到服务器。当它被调用时,它实际上在客户端进程中运行。这非常酷,而且远非微不足道。它之所以有效,是因为 rpyc 是对称的
  2. 为了超灵活,使用 rpyc 的经典模式
于 2013-10-26T16:50:11.323 回答