Sometimes, we want to do interprocess communication in Python.
In this article, we’ll look at how to do interprocess communication in Python.
How to do interprocess communication in Python?
To do interprocess communication in Python, we can use the multiprocessing library to send and receive commands.
For instance, in the server, we write
from multiprocessing.connection import Listener
address = ('localhost', 6000)
listener = Listener(address, authkey=b'secret password')
conn = listener.accept()
print('connection accepted from', listener.last_accepted)
while True:
msg = conn.recv()
if msg == 'close':
conn.close()
break
listener.close()
to call listener.accept to listen for for commands.
We then add an infinite while loop that ends when msg is 'close'.
We get msg from conn.recv which gets the received message.
In the client, we write
from multiprocessing.connection import Client
address = ('localhost', 6000)
conn = Client(address, authkey=b'secret password')
conn.send('close')
conn.close()
to create a Client object and call send to send a message to the server at the given address.
Conclusion
To do interprocess communication in Python, we can use the multiprocessing library to send and receive commands.