[英]Kill a python subprocess that does not return
TLDR 我想在它仍在运行时杀死一个像 top 这样的子进程
我正在使用 Fastapi 在输入上运行命令。 例如,如果我输入 top 我的程序运行命令,但由于它没有返回,此时我必须使用时间延迟然后杀死/终止它。 但是我希望能够在它仍在运行时将其杀死。 但是目前它不会运行我的 kill 命令,直到时间用完。 这是运行进程的当前代码:
@app.put("/command/{command}")
async def run_command(command: str):
subprocess.run([command], shell=True, timeout=10)
return {"run command"}
并杀死它
@app.get("/stop")
async def stop():
proc.kill()
return{"Stop"}
我是 fastapi 的新手,所以我将不胜感激
这是因为subprocess.run
本身阻塞 - 您需要在后台运行 shell 命令,例如使用Popen
from subprocess import Popen
process = None
@app.get("/command/{command}")
async def run_command(command: str):
global process
process = Popen([command]) # something long running
return {"run command"}
@app.get("/stop")
async def stop():
process.kill()
return {"Stop"}
但请注意一件事,如果命令包含空格 Popen 应该获取部件列表,因此运行命令“sleep 10”应该是Popen(["sleep", "10"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.