Python自动执行Linux下终端指令

2019-11-15  本文已影响0人  生活就是爱

一、遇到什么问题

需要写一段代码,自动执行以下两个命令
1.查找被占用端口:lsof -i:33539


2019-11-15 11-23-33屏幕截图.png

从报错信息中可以看出,是端口33539被占用,因此我们查询是哪一个进程占用了该端口
2.杀死指定进程:kill 3719

二、如何解决

python的os模块提供了popensystem两个方法可以执行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)

参考资料:

Python - 调用终端执行命令
os.system如何传参

上一篇 下一篇

猜你喜欢

热点阅读