[英]Kill the background process executed by python
I have a script 我有一个脚本
import os
os.system('python manage.py runserver')
The script starts django server (no matter what it does, it can be any command which evaluates until ctrl+c
or another key shortcut is pressed). 该脚本启动django服务器(无论它做什么,它可以是任何评估的命令,直到按下
ctrl+c
或其他键快捷键)。
What I want is to stop the server by any way but not by killing it by pid. 我想要的是以任何方式停止服务器,但不是通过pid杀死它。
What I've tried: 我尝试过的:
I tried to use subprocess
lib and it's kill
command as described here: How to terminate a python subprocess launched with shell=True 我尝试使用
subprocess
lib和它的kill
命令,如下所述: 如何终止使用shell = True启动的python子进程
But it does not help. 但它没有帮助。 As I guess, the reason is: we are killing not the
manage.py runserver
process but the process which evaluates python manage.py runserver
. 我猜,原因是:我们不是杀死
manage.py runserver
进程,而是查看python manage.py runserver
的进程。 So, after killing process, server is still running. 因此,在查杀过程后,服务器仍在运行。
Also I've tried use terminate
method: 我也尝试过使用
terminate
方法:
p = subprocess.Popen('python manage.py runserver', stdout=subprocess.PIPE, shell=True)
time.sleep(5)
p.terminate()
As I think it should work this way: server starts and after 5 seconds it stops, but it never stops. 我认为它应该以这种方式工作:服务器启动,并在5秒后停止,但它永远不会停止。
Is there any way to kill the process? 有没有办法杀死这个过程?
This sounds dubious. 这听起来很可疑。 Please don't do that!
请不要那样做!
Django recommends using WSGI to allow the webserver (Apache, NginX, etc) to load and unload Django as necessary automatically. Django建议使用WSGI允许Web服务器(Apache,NginX等)根据需要自动加载和卸载Django。 Here's how to do that .
这是怎么做的 。 Also, Django's built-in web server isn't considered secure or scalable .
此外,Django的内置Web服务器不被认为是安全的或可扩展的 。 In general, don't do that!
一般来说,不要这样做!
If you're averse to using WSGI, you can also do a proxypass with Apache , NginX , etc. The Django server itself can be managed by any number of system service tools, like init.d or supervisord . 如果你不愿意使用WSGI,你也可以做的ProxyPass与Apache , Nginx的 ,等等Django的服务器本身可以通过任意数量的系统服务工具,如管理的init.d或supervisord 。
To directly answer to your question, you could use process.terminate()
to kill the active process launched with subprocess
, but it's a terrible idea to run your server by yourself with a python script when so many other great tools exist. 要直接回答您的问题,您可以使用
process.terminate()
来subprocess
使用subprocess
进程启动的活动进程,但是当存在许多其他很棒的工具时,使用python脚本自行运行服务器是一个糟糕的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.