This sounds like a job for the Pyro4 package. Here's an example based on their "Simple Example", with some extra code to start the nameserver automatically and listen over a network.
First use this command on each machine to install Pyro4:
pip install pyro4
On the server, save this script as server.py
and then run it in a terminal window via python server.py
:
# saved as server.py
import Pyro4, Pyro4.naming
import socket, threading
# Define an object that will be accessible over the network.
# This is where all your code should go...
@Pyro4.expose
class MessageServer(object):
def show_message(self, msg):
print("Message received: {}".format(msg))
# Start a Pyro nameserver and daemon (server process) that are accessible
# over the network. This has security risks; see
# https://pyro4.readthedocs.io/en/stable/security.html
hostname = socket.gethostname()
ns_thread = threading.Thread(
target=Pyro4.naming.startNSloop, kwargs={'host': hostname}
)
ns_thread.daemon = True # automatically exit when main program finishes
ns_thread.start()
main_daemon = Pyro4.Daemon(host=hostname)
# find the name server
ns = Pyro4.locateNS()
# register the message server as a Pyro object
main_daemon_uri = main_daemon.register(MessageServer)
# register a name for the object in the name server
ns.register("example.message", main_daemon_uri)
# start the event loop of the main_daemon to wait for calls
print("Message server ready.")
main_daemon.requestLoop()
On the client, save this as client.py
and run it with python client.py
:
# saved as client.py
import Pyro4
import sys
print("What is your message?")
msg = sys.stdin.readline().strip()
# lookup object uri on name server and create a proxy for it
message_server = Pyro4.Proxy("PYRONAME:example.message")
# call method on remote object
message_server.show_message(msg)
Note that setting up Pyro to listen over your network is a security risk. So you should read their section on security before you go ahead with this. But this should be enough to get you started.
If you want a solution that just uses the standard library, you could take a look at my socket-based client-server setup in a different answer. Or you might consider setting up a flask
webserver on the server, and then using urllib2
on the client to access the server and invoke the correct action (probably via a GET
or POST
request). But those are both more difficult than this.
Another option would be to use a different interprocess communication package such as PyZMQ, redis, mpi4py or maybe zmq_object_exchanger. See this question for some ideas.