Reputation: 423
I am trying to use subprocess.popen to execute another python script that creates a listening socket. I want to pass it a default number for the port to bind on. I also want to catch if the port is already in use and the bind fails. If it fails then I want to call subprocess.popen again and pass it another number to try and bind to.
first.py
import subprocess
p = subprocess.Popen(["python3.7", "test.py", "4444"], shell=False)
#If p is success (bind succeeded) then I want to continue processing code.
#Else I want to increment the port and try again.
start.py
import socket, sys
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = int(sys.argv[1]) # Port to listen on (non-privileged ports are > 1023)
def stuff():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((HOST, PORT))
except:
print("failed to bind")
return 1
s.listen()
print("Listening")
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
stuff()
Upvotes: 0
Views: 78
Reputation: 168967
A couple of things:
Just returning 1
from a function called won't make your process's exit code 1
.
Either do sys.exit(stuff())
or just call sys.exit(1)
in stuff()
.
You can wait for a subprocess to succeed or fail with p.wait()
, after which you can look at p.returncode
.
In your case, you'll probably want to do something like
import subprocess
p = subprocess.Popen(["python3.7", "test.py", "4444"], shell=False)
try:
p.wait(2)
except subprocess.TimeoutExpired:
pass # it was probably successful and is now listening
else:
if p.returncode == 1:
pass # nope
And, of course, you could do this with just threads instead of subprocesses.
Upvotes: 1