【问题标题】:How to interact with Running Python Script如何与运行 Python 脚本进行交互
【发布时间】:2013-10-26 16:01:19
【问题描述】:

当我的主脚本正在运行时

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)

【问题讨论】:

  • 你的意思是:python main.py & python otherscript.py
  • 他可能想要线程。
  • 哇,不,我在启动时运行 main.py。然后 otherscript.py 在其他时间(只要用户想要)
  • @KingofGames 所以你想访问其他 python 进程的变量?
  • 我想访问另一个进程的对象

标签: python interprocess inter-process-communicat


【解决方案1】:

使用rpyc。它干净、直观且非常强大。

基本上,您编写一个 service 类来公开您想要的任何接口(例如,它有一个返回您需要的全局变量的方法),创建一个 server与该服务关联的对象,然后启动它。然后,在客户端中,您使用 client 对象进行连接,并调用该函数,该函数从服务器进程返回变量。

编辑:运行 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 引用)从客户端传递到服务器。当它被调用时,它实际上是在 client 进程中运行的。这非常酷,而且远非微不足道。它之所以有效,是因为 rpyc 是 symmetric
  2. 要获得超灵活性,请使用 rpyc 的classic mode

【讨论】:

  • 这看起来很有趣,我去看看。不过,这不是有点矫枉过正吗?两个脚本都在同一台计算机上运行。
  • rpyc 在相同或不同的计算机上需要相同的工作量。好处是它是一个 RPC 解决方案,除了你的 python 逻辑,你不需要担心任何事情。 IE。没有套接字,没有 XML(如 SOAP),没有花哨的协议,没有序列化等。这实际上很简单。当我找到时间时,我会在我的答案中添加代码。
  • 使用 mmap 会更快吗?
  • 导入大约需要 0.2 秒。我的脚本需要更短的响应时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多