How to 'clear' the port when restarting django runserver

前端 未结 19 2186
盖世英雄少女心
盖世英雄少女心 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: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[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.

提交回复
热议问题