import psutil
def kill_by_port(port):
for conn in psutil.net_connections():
if conn.laddr.port == port and conn.status == 'LISTEN':
p = psutil.Process(conn.pid)
p.terminate()
仅适用于windows
import subprocess
import re
def kill_by_port(port):
c = subprocess.getoutput(f'netstat -ano | findstr {port} |findstr LISTENING ')
pids = re.findall('(\d+)\n', c)
for pid in set(pids):
if int(pid) > 0:
subprocess.run(f"taskkill /pid {pid} -f")