这听起来像是Pyro4 package 的工作。这是一个基于他们的"Simple Example" 的示例,其中包含一些额外的代码来自动启动名称服务器并通过网络进行侦听。
首先在每台机器上使用这个命令安装Pyro4:
pip install pyro4
在服务器上,将此脚本保存为server.py,然后通过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()
在客户端,将其保存为client.py 并使用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)
请注意,将 Pyro 设置为通过您的网络进行监听存在安全风险。所以你应该在继续之前阅读他们的section on security。但这应该足以让您入门。
如果您想要一个只使用标准库的解决方案,您可以查看我在a different answer 中的基于套接字的客户端-服务器设置。或者您可以考虑在服务器上设置flask 网络服务器,然后在客户端使用urllib2 访问服务器并调用正确的操作(可能通过GET 或POST 请求)。但这些都比这更困难。
另一种选择是使用不同的进程间通信包,例如 PyZMQ、redis、mpi4py 或 zmq_object_exchanger。请参阅this question 了解一些想法。