I am using the subprocess module. And using Popen to start the server subprocess.
# create a process for the server to run on
process = Popen("poetry run -vvv python ./app/server.py", cwd="./api", stderr=PIPE, stdin=PIPE, stdout=PIPE)
The script posts some data on the server and when all the response are received i want to close the subprocess.
server.py
starts a fastapi server with uvicorn listening on localhost:8000
.
I tried using :
- kill()
- terminate()
- send_signal(CTRL_C_EVENT)
- send_signal(SIGINT)
- send_signal(SIGTERM)
- os.kill(process.pid, SIGINT)
- os.kill(process.pid, SIGTERM)
- os.kill(process.pid, SIGKILL)
- process.stdin.write(b’q’) + process.stdin.flush()
- subprocess.call(“taskkill /f /pid {pid}”.format(pid=process.pid))
None of these solution worked. Everytime i need to run these commands to kill the process that is still running.
netstat -a -o -n | findstr 8000
to find the pid of the process, tasklist | findstr pid
to assure that
it’s a python console and taskkill /f /pid pid
to kill the process.
I call this method at the end of the script. And i noticed that the pid in the error didn’t match the pid i got when running the commands from last paragraph.
def kill_subprocess(subp):
subp.send_signal(signal.CTRL_C_EVENT)
subp.terminate()
if subp.wait() != 0:
print("subprocess return code = {code}".format(code=subp.returncode))
raise RuntimeError("subprocess {pid} still running".format(pid=subp.pid))
Oscar Baume is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.