Python 中的进程间通信:探索双向通信的选项
进程间通信对于实现不同 Python 运行时之间的交互至关重要。已经尝试了各种方法,包括:
多处理救援
Python 社区通过多处理库提供了一个优雅的解决方案。它为进程提供了在套接字上构建的侦听器和客户端,从而促进任意 Python 对象的交换。
服务器端实现:
<code class="python">from multiprocessing.connection import Listener # Define the server address address = ('localhost', 6000) # Create a listener with a secret password for authentication listener = Listener(address, authkey=b'secret password') # Accept incoming connections conn = listener.accept() print('Connection accepted from', listener.last_accepted) # Process incoming messages while True: msg = conn.recv() # Handle the message if msg == 'close': # End the communication conn.close() break listener.close()</code>
客户端- side实现:
<code class="python">from multiprocessing.connection import Client # Specify the server address address = ('localhost', 6000) # Connect to the server using the secret password conn = Client(address, authkey=b'secret password') # Send commands to the server conn.send('close') # Send arbitrary objects as well # conn.send(['a', 2.5, None, int, sum]) # Close the connection conn.close()</code>
通过使用此解决方案,您可以轻松地在Python中建立健壮且高效的进程间通信,满足您对不同进程之间的消息传递和双向通信的需求。
以上是Python 的多处理库如何促进双向进程间通信?的详细内容。更多信息请关注PHP中文网其他相关文章!