1

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).

What I want is to stop the server by any way but not by killing it by 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

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. So, after killing process, server is still running.

Also I've tried use terminate method:

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.

Is there any way to kill the process?

Community
  • 1
  • 1
imkost
  • 8,033
  • 7
  • 29
  • 47
  • 1
    have you created a new process group as the answer from the question you've linked recommends? `runserver` doesn't demonize the server process therefore the recipe should work. – jfs Oct 21 '14 at 07:06
  • 2
    don't use `stdout=PIPE` if you don't read from the pipe. Use [DEVNULL instead if you want to discard the output](http://stackoverflow.com/q/11269575/4279) – jfs Oct 21 '14 at 07:08
  • Thank you so much! I've just tried again the answer from the question i've linked and... everything works. I don't know why it didn't work for the first time, but now it does exactly what I want. So thank you for pointing me again to that question and additional thank you for DENVULL (the undesirable output was my second problem) – imkost Oct 21 '14 at 08:17

1 Answers1

3

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. Here's how to do that. Also, Django's built-in web server isn't considered secure or scalable. 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.

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.

Community
  • 1
  • 1
VooDooNOFX
  • 4,674
  • 2
  • 23
  • 22
  • the thing is: for the development I want one command to start local webserver, coffee & less compilers. And one command to kill them all simultaneously – imkost Oct 21 '14 at 05:27
  • `terminate` command does not work, updated my question to show what I do with terminate – imkost Oct 21 '14 at 05:31