How to 'clear' the port when restarting django runserver

前端 未结 19 2126
盖世英雄少女心
盖世英雄少女心 2020-12-12 11:23

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

相关标签:
19条回答
  • 2020-12-12 11:47
    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.

    0 讨论(0)
  • 2020-12-12 11:47

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

    0 讨论(0)
  • 2020-12-12 11:48

    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.

    0 讨论(0)
  • 2020-12-12 11:49

    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.

    0 讨论(0)
  • 2020-12-12 11:51

    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.

    0 讨论(0)
  • 2020-12-12 11:53
    netstat -tulpn |grep 8000|awk '{print $7}'|cut -d/ -f 1|xargs kill
    
    0 讨论(0)
提交回复
热议问题