Problem quite old but I met similar when I was running flask server with subprocess.Popen
in conftest.py
with pytest
in docker container on Mac OS.
This piece of code is not working for me (in conftest.py
)
flask_server_proc = subprocess.Popen([
'python', 'code/flask_server/main.py',
'--local'
])
flask_server_proc.kill()
Parent process was killed but server still was running and answering requests.
So I did this:
import psutil
import subprocess
server = subprocess.Popen([
'python', 'code/flask_server/main.py',
'--mysql-user', 'root',
'--mysql-password', 'pass',
'--mysql-host', 'mysql',
'--local-artifact-store'
])
# Here I check if server is up. For example with some health check
# url. Sleep mimics it.
import time
time.sleep(10)
print(server.pid)
# Somewhere here you will call 'yield server'. This is just snippet
# with potential solution of problem so no yielding it.
# The next part should be run after 'yield server'.
# This should kill server.
# server.kill()
# Actually it should be one such process like flask.
flask_to_kill: List[psutil.Process] = []
for process in psutil.process_iter():
if 'code/flask_server/main.py' in process.cmdline():
flask_to_kill.append(process)
def on_terminate(proc: psutil.Process):
print("process {} terminated with exit code {}".format(proc, proc.returncode))
for f in flask_to_kill:
f.terminate()
gone, alive = psutil.wait_procs(flask_to_kill, timeout=3, callback=on_terminate)
for to_stab in alive:
to_stab.kill()
so looks like remedy is to use psutil
package to kill server after tests.
Happy hacking!