对于一般的 直接调用 process.kill() 即可 ,当使用参数 shell=True时:
process = subprocess.Popen('xx xx xx xx‘, shell=True)
if os.name == 'nt': # windows
subprocess.Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))
else:
os.kill(process.pid, signal.SIGTERM)
其他:
使用 psutil 查询本机监听某个端口的进程:
def get_process_by_port(port):
connections = psutil.net_connections()
for connection in connections:
if connection.status == 'LISTEN' and connection.laddr.port == port:
return psutil.Process(connection.pid)
return None