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 t
sudo lsof -t -i tcp:8000 | xargs kill -9
If you want to free 8000 port than just copy command and paste in your cmd it will ask for sudo password. And then you are good to go.
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.
If the ps aux
command (as per Meilo's answer) doesn't list the process that you wanted to kill but shows the port active in netstat -np | grep 8004
network activity, try this command (worked on Ubuntu).
sudo fuser -k 8004/tcp
where as, 8004 is the port number that you want to close. This should kill all the processes associated with port 8004.
Happened so often that I wrote an alias to kill the process with python
in the name (careful if you have other such processes). Now I just run (no Ubuntu)
kill $(ps | grep "python" | awk "{print $1}")
You can even add python manage.py runserver ...
to the same alias so you can restart with two keystrokes.
netstat -tulpn |grep 8000|awk '{print $7}'|cut -d/ -f 1|xargs kill