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:
JavaScript
x
6
1
def dosomething(args):
2
# do something
3
return information
4
while True:
5
# Do something in a loop
6
script2:
JavaScript
1
3
1
# "import" the background process
2
print(backgroundprocess.dosomething(["hello", (1, 2, 3)]))
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
JavaScript
1
31
31
1
from xmlrpc.server import SimpleXMLRPCServer
2
from xmlrpc.server import SimpleXMLRPCRequestHandler
3
4
class RequestHandler(SimpleXMLRPCRequestHandler):
5
rpc_paths = ('/RPC2',)
6
7
# Create server
8
with SimpleXMLRPCServer(('localhost', 8000),
9
requestHandler=RequestHandler) as server:
10
server.register_introspection_functions()
11
12
# Register pow() function; this will use the value of
13
# pow.__name__ as the name, which is just 'pow'.
14
server.register_function(pow)
15
16
# Register a function under a different name
17
def adder_function(x, y):
18
return x + y
19
server.register_function(adder_function, 'add')
20
21
# Register an instance; all the methods of the instance are
22
# published as XML-RPC methods (in this case, just 'mul').
23
class MyFuncs:
24
def mul(self, x, y):
25
return x * y
26
27
server.register_instance(MyFuncs())
28
29
# Run the server's main loop
30
server.serve_forever()
31
Client Example
JavaScript
1
10
10
1
import xmlrpc.client
2
3
s = xmlrpc.client.ServerProxy('http://localhost:8000')
4
print(s.pow(2,3)) # Returns 2**3 = 8
5
print(s.add(2,3)) # Returns 5
6
print(s.mul(5,2)) # Returns 5*2 = 10
7
8
# Print list of available methods
9
print(s.system.listMethods())
10