Use python to close the process based on the port number
- 2021-01-22 05:16:25
- OfStack
As we know, during web development, the whole project needs to be started repeatedly during debugging, so the port occupied by the last project cannot be used when the next project is started, because the port occupied by the last project has not been released, but the manual closing method is as follows:
lsof -i:12345
You get pid and you get kill-9 pid
10 points trouble, so can we close the port occupied in the last time when we start web project?
Of course it does, let's take flask as an example (note, when copying the code below, don't just copy it with the mouse, but use view plain in the upper left corner, because the csdn blog will display the right side of "+str(port)+" with 5 single quotes, and the front of "kill-9" with 5 single quotes) :
#-*- encoding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
from flask import Flask
# Generating the 1 An instance
app = Flask(__name__)
# call app Routing method based on
@app.route('/')
def hello_world():
return '<h1> Hello World!</h1>'
def killport(port):
command='''kill -9 $(netstat -nlp | grep :'''+str(port)+''' | awk '{print $7}' | awk -F"/" '{ print $1 }')'''
os.system(command)
# Start to perform
if __name__ == '__main__':
# Open Debug Window
app.debug = True;
#run You can specify host Parameter, specifying ip,0.0.0.0 Represents the whole network segment
#app.run()
port=12345
killport(port)
app.run(host='0.0.0.0',port=port);
# Test method: curl -i 127.0.0.1:12345/