I am running a flask server on localhost from within a subprocess.Popen process.
I want to know what port was allocated to the flask server in this process without blocking the calling process. I would then use the localhost:port to talk to the flask app.
This is server.py:
# server.py
import Flask
app = Flask(__name__)
@app.route('/')
def call_method():
return 'Hello'
if __name__ == '__main__':
app.run()
Option 1: prints port to stdout, but I cannot get to it programmatically. Also, blocks the calling process
process = subprocess.Popen(['python', 'server.py'])
Option 2: traps the stdout, but gets only what is buffered at the time of launching the process. This may not contain the line containing the port. But, since I am piping stdout, this also blocks the caller shell.
process = subprocess.Popen(['python', 'server.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if process.stdout:
for line in process.stdout.readline():
print(line)
How do I get the port from the returned process, and not block the calling process?
This whole answer feels a bit dirty, but it works nonetheless:
server.py:
run.py:
python run.py
prints the port number and keeps the server running in the background. It works on both windows and linux.