So say there are two running codes: script1 and script2. I want script2 to be able to run a function in script1. script1 will be some kind of background process that will run “forever”.
The point is to be able to make an API for a background process, E.G. a server.
The unclean way to do it would be to have a file transmit the orders from script2. script1 would then execute it with exec()
. However, I would like to use a module or something cleaner because then I would be able to output classes and not only text.
EDIT: example:
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)]))
The execution would look like this:
- Run script1
- Run script2 in a parallel window
Advertisement
Answer
Summary
The XMLRPC modules are designed for this purpose.
The docs include a worked out example for a server (script1) and a client (script2).
Server Example
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()
Client Example
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())