Python - Remote Procedure Call



Remote Procedure Call (RPC) system enables you to call a function available on a remote server using the same syntax which is used when calling a function in a local library. This is useful in two situations.

  • You can utilize the processing power from multiple machines using rpc without changing the code for making the call to the programs located in the remote systems.
  • The data needed for the processing is available only in the remote system.

So in python we can treat one machine as a server and another machine as a client which will make a call to the server to run the remote procedure. In our example we will take the localhost and use it as both a server and client.

Running a Server

The python language comes with an in-built server which we can run as a local server. The script to run this server is located under the bin folder of python installation and named as classic.py. We can run it in the python prompt and check its running as a local server.

python bin/classic.py

When we run the above program, we get the following output −

INFO:SLAVE/18812:server started on [127.0.0.1]:18812

Running a Client

Next we run the client using the rpyc module to execute a remote procedure call. In the below example we execute the print function in the remote server.

import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute("print('Hello from Tutorialspoint')")

When we run the above program, we get the following output −

Hello from Tutorialspoint

Expression Evaluation through RPC

Using the above code examples we can use python’s in-built functions for execution and evaluation of expressions through rpc.

import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute('import math')
conn.eval('2*math.pi')

When we run the above program, we get the following output −

6.283185307179586
Advertisements