一、遇到什么问题
需要写一段代码,自动执行以下两个命令
1.查找被占用端口:lsof -i:33539
2019-11-15 11-23-33屏幕截图.png
从报错信息中可以看出,是端口33539被占用,因此我们查询是哪一个进程占用了该端口
2.杀死指定进程:kill 3719
二、如何解决
python的os
模块提供了popen
、system
两个方法可以执行Linux下终端命令
import os
val = os.popen('lsof -i:33539').readlines()
print(val)
mark_index = 0
for temp in val:
temp = temp.split(" ")
temp = list(filter(None, temp))
#print(">>>>>>>>>:", temp)
if "PID" in temp:
mark_index = temp.index("PID")
elif mark_index:
pid_num = int(temp[mark_index])
#print(pid_num)
os.system("kill %d" %pid_num)
网友评论