如何在不单击“CTRL+C”的情况下通过cmd中的命令停止Django服务器?

2024-04-24 12:00:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在PySide2上为Controldjango项目(在按钮上运行服务器和停止服务器)编写桌面应用程序(这并不重要)。我只实现了启动服务器,但我不能添加停止服务器,因为停止服务器是在cmd中单击按钮"CTRL + C",我现在不知道如何将单击按钮解释为代码或任何问题的答案。你知道吗

这是一个“运行服务器”的例子,我需要一些“停止服务器”的帮助

os.chdir(ui.lineEdit.text())   # Change directory
os.system("python manage.py runserver")   # Run server in this

Tags: 项目答案代码服务器cmd应用程序uios
2条回答

Ctrl+C是终端解释的东西。它将向正在运行的进程发送一个SIGINT信号。因此,终止应用程序的不是Ctrl+C本身。你知道吗

您也可以这样做,例如首先用^{}打开一个进程,然后最终发送一个信号:

from subprocess import Popen
from signal import SIGINT

# start the process
p = Popen(['python', 'manage.py', 'runserver'])

# now stop the process
p.send_signal(SIGINT)
p.wait()

下面是另一个可以从Python的system调用的方法。。。这对于创建别名来终止当前用户的现有runserver进程(以防它们卡住)也很方便:

# Kill any Django runserver instances for the current user
alias kill-runserver="ps -eaf | grep 'manage.py runserver' | grep "'$USER'" | grep -v grep | awk '{print "'$2'"}' | xargs kill -9"

创建别名后,只需运行kill-runserver。如果您想更安全一点,可以从kill命令中删除-9。你知道吗

相关问题 更多 >