Get port from flask localhost app running in a subprocess Popen process

922 Views Asked by At

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?

1

There are 1 best solutions below

0
On

This whole answer feels a bit dirty, but it works nonetheless:

server.py:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def call_method():
    return 'Hello'

if __name__ == '__main__':
    app.run()

run.py:

import subprocess
p = subprocess.Popen(['python', 'server.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

flask_start_string = ''

while True:
    flask_start_string += p.stdout.readline().decode('utf-8')
    if '(Press CTRL+C to quit)' in flask_start_string:
        port = flask_start_string.split(' * Running on http://127.0.0.1:')[1].split('/ (Press CTRL+C to quit)')[0]
        break

print(port)

python run.py prints the port number and keeps the server running in the background. It works on both windows and linux.