使用Python检查端口占用情况 发表于 2016-04-20 | 使用adb的时候,有时候会发现5037端口被其他程序占用了。于是有了以下这个脚本,检查端口被占用的情况,并结束该进程。 开发环境:Python3.5+Win10+Pycharm 123456789101112131415161718192021222324252627282930313233343536373839404142434445#! /usr/bin/env python# -*- coding: UTF-8 -*-import osdef is_port_used(port=5037, kill=False): cmd = 'netstat -ano | findstr {} | findstr LISTENING'.format(port) print(cmd) result = os.popen(cmd).read() print(result) pid = None if result != '': try: pid = result.split()[-1] result = os.popen('tasklist /FI "PID eq {0}'.format(pid)).read() """:type: str """ print(result) position = result.rfind('=====') program_name = result[position + 5:].split()[0] print("占用的程序是{}".format(program_name)) result = os.popen('wmic process where name="{0}" get executablepath'.format(program_name)).read() result = result.split() print("占用的程序所在位置:{}".format(result[1])) cmd = "explorer {0}".format(os.path.dirname(result[1])) execute_cmd(cmd) # 打开所在文件夹 except Exception: import traceback traceback.print_exc() finally: if kill: if not pid: raise Exception("pid is None") print(os.popen("taskkill /F /PID {0}".format(pid)).read()) # 结束进程 else: print('{}端口没有被占用'.format(port))if __name__ == '__main__': is_port_used() input() 运行结果: 12345678910netstat -ano | findstr 5037 | findstr LISTENING TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 16600映像名称 PID 会话名 会话# 内存使用========================= ======== ================ =========== ============adb.exe 16600 Console 1 3,868 K占用的程序是adb.exe占用的程序所在位置:C:\Android\sdk\platform-tools\adb.exe