简体   繁体   English

如何与运行Python脚本进行交互

[英]How to interact with Running Python Script

While my main script is running 我的主脚本正在运行

class Blah():
    update=0

    def testthings(function):
        return function(9)

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

How can I run an independent script to have access to the 'main variable' (defined in my main script) while the main script is running? 在主脚本运行时,如何运行独立脚本以访问“主变量”(在我的主脚本中定义)?

Something like this would be useful 像这样的东西会很有用

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

Use rpyc . 使用rpyc It's clean, intuitive, and very powerful. 它干净,直观,功能强大。

Basically, you write a service class which exposes whichever interface you'd like (eg it has a method which returns that global variable you need), create a server object associated with that service , and start it. 基本上,你编写一个服务类,它暴露你想要的任何接口(例如,它有一个返回你需要的全局变量的方法),创建一个与该服务相关的服务器对象,然后启动它。 Then, in a client, you connect using a client object, and call that function, which returns the variable from the server process. 然后,在客户端中,使用客户端对象进行连接,并调用该函数,该函数从服务器进程返回变量。

EDIT: code sample for running the rpyc server, and connecting an rpyc client 编辑:用于运行rpyc服务器和连接rpyc客户端的代码示例

rpyc_main.py 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.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()

output 产量

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

Notes: 笔记:

  1. a lambda object (actually, a rpyc-reference to that object) is passed from the client to the server. lambda对象(实际上是对该对象的rpyc引用)从客户端传递到服务器。 when it is being called, it actually runs in the client process. 当它被调用时,它实际上在客户端进程中运行。 This is super cool and far from trivial. 这非常酷,远非琐碎。 It works because rpyc is symmetric 它的工作原理是因为rpyc是对称的
  2. for ultra-flexibility, use rpyc's classic mode 为了超灵活,使用rpyc的经典模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM