import subprocess
import os
def getPid(port):
"""获取进程pid"""
try:
back = subprocess.Popen("""lsof -i:%s | awk 'NR==2{print $2}'""" % (port), shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
data = back[0].decode().split('\n')
except Exception as e:
print('error:', e)
data = []
print('端口对应的pid:', data)
return data
def killPid(pid):
"""杀死进程"""
cmd = "kill -s 9 {}".format(pid)
print(cmd)
result = os.system(cmd)
if result == 0:
print("kill {} success".format(pid))
else:
print("kill {} error".format(pid))
print('- -- -- --- ---- --- --- ---- --- --- -- --')
print('end')
def run(port):
data = getPid(port)
pid = data[0]
print('pid:', pid)
print('pid:', len(pid))
if len(pid) > 0:
killPid(pid)
else:
print('未查到端口-{}进程:'.format(port))
run(8001)