How to 'clear' the port when restarting django runserver

Viewed 74954

Often, when restarting Django runserver, if I use the same port number, I get a 'port is already in use' message. Subsequently, I need to increment the port number each time to avoid this.

It's not the case on all servers, however, so I'm wondering how I might achieve this on the current system that I'm working on?

BTW, the platform is Ubuntu 8.10

19 Answers

You're getting that message because the server is already running (possibly in the background). Make sure to kill the process (bring it to the foreground and press ctrl-c) to stop the process.

No, he's not an idiot guys. Same thing happens to me. Apparently it's a bug with the python UUID process with continues running long after the django server is shutdown which ties the port up.

Like mipadi said, you should be terminating the server (ctrl+c) and returning to the command prompt before calling manage.py runserver again.

The only thing that could be disrupting this would be if you've somehow managed to make runserver act as a daemon. If this is the case, I'm guessing you're using the Django test server as the actual web server, which you should NOT do. The Django test server is single threaded, slow and fragile, suitable only for local development.

In Leopard, I bring on the Activity Monitor and kill python. Solved.

Add the following library in manage.py

import os
import subprocess
import re

Now add the following python code after if __name__ == "__main__":

ports = ['8000']
popen = subprocess.Popen(['netstat', '-lpn'],
                         shell=False,
                         stdout=subprocess.PIPE)
(data, err) = popen.communicate()
pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern)
for line in data.split('\n'):
    match = re.match(prog, line)
    if match:
        pid = match.group('pid')
        subprocess.Popen(['kill', '-9', pid])

This will first find the process id of port 8000 , will kill it and then restart your project. Now each time you don't need to kill the pid manually.

Related