1

I'm writing my desktop app on PySide2 (it's not important) for control Django project (run server and stop server on buttons). I realized only start server, but I can't add stop server, because stop server is click on buttons "CTRL + C" in cmd and I don't now how to interpret clicks on buttons into code or any answers for this question.

Here is an example for "RUN server" and I need some help for "STOP server"

os.chdir(ui.lineEdit.text())   # Change directory
os.system("python manage.py runserver")   # Run server in this
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sasha Zuev
  • 29
  • 5

2 Answers2

5

Ctrl+C is something a terminal interprets. It will send a SIGINT signal to the process that is running. So it is not the Ctrl+C itself that terminates the application.

You can do the same, for example by first opening a process with Popen(..), and then eventually send a signal:

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()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks! Your answer help me partially (For the start server), but I tried to stop server by your method and failed.But I found a solution: stop server through killing task from task manager. – Sasha Zuev Sep 18 '19 at 15:46
  • @SashaZuev: then usually that means the process is "zombied". You can use a `SIGTERM` as well, but usually killing a process is not a good idea at all. – Willem Van Onsem Sep 18 '19 at 16:15
  • okey, I will consider this. Don't be surprised with my decisions - I recently started programming)) – Sasha Zuev Sep 18 '19 at 17:06
  • using `os.kill(pid, signal.SIGINT)` load existing process by pid, [ref](https://stackoverflow.com/a/17858114/2268680) – Kamil Jan 26 '21 at 09:14
2

Here's another method that you could call from Python's system... this is also handy to make an alias to kill existing runserver processes for the current user (in case they get stuck):

# 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"

After creating the alias, just run kill-runserver. If you want to be a little bit safer, eliminate the -9 from the kill command.

FlipperPA
  • 13,607
  • 4
  • 39
  • 71