I have a process.py
script:
from multiprocessing.connection import Listener
with Listener(('localhost', 6000)) as listener:
with listener.accept() as connection:
message = connection.recv()
# [...]
connection.send(message)
I launch this script in a thread (to avoid blocking the main thread) with:
import threading, subprocess
threading.Thread(target=lambda: subprocess.run(['python', 'process.py'])).start()
But sometimes I want to wait (block the main thread) until my process has launched.
Here is what I do:
from multiprocessing.connection import Client
nAttempts = 0
while True:
try:
with Client(('localhost', 6000)) as connection:
connection.send(nAttempts)
message = connection.recv()
# [...]
break
except ConnectionRefusedError:
nAttempts += 1
pass
Is there a better approach?
The program tries ~282 connections before being able to connect, can it be a problem?