假设有两个正在运行的代码:script1和script2。我希望script2能够运行script1中的函数。script1将是某种后台进程;永远";。
关键是能够为后台进程(例如服务器(创建API。
不干净的做法是让一个文件传输script2中的命令。script1将使用CCD_ 1执行它。然而,我想使用一个模块或更干净的东西,因为这样我就可以输出类,而不仅仅是文本。
编辑:示例:
script1:
def dosomething(args):
# do something
return information
while True:
# Do something in a loop
script2:
# "import" the background process
print(backgroundprocess.dosomething(["hello", (1, 2, 3)]))
执行情况如下:
- 运行script1
- 在并行窗口中运行script2
摘要
XMLRPC模块就是为此目的而设计的。
这些文档包括一个服务器(script1(和一个客户端(script2(的示例。
服务器示例
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x, y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'mul').
class MyFuncs:
def mul(self, x, y):
return x * y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
客户端示例
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3)) # Returns 2**3 = 8
print(s.add(2,3)) # Returns 5
print(s.mul(5,2)) # Returns 5*2 = 10
# Print list of available methods
print(s.system.listMethods())