环境
- ubuntu 18.04 64bit
- python 3.8
前言
在实际项目中,经常会有这样的需求:
- 某个进程已经在后台运行了,现在想通过进程名来杀掉它
- 通过代码的方式启动一个新的进程来运行特定的
shell
指令,在需要的时候再杀掉该进程
那本文就来解决这个问题
示例代码
进程已经在后台运行的情况
这里由于进程已经执行了,大部分情况下是不知道进程的 ID
号的,也就是 pid
,因此,很多时候是要通过进程名去过滤并得到 pid
比如我在终端执行了命令,这是个长时间运行的进程
watch -n 1 nvidia-smi
然后,在 python
中就可以这样去杀掉它
import os, signal, subprocess
def process():
# 由用户输入进程名
name = input("Enter process Name: ")
try:
# 通过进程名来过滤ps ax的结果
for line in os.popen("ps ax | grep " + name + " | grep -v grep"):
print('line: {}'.format(line))
fields = line.split()
print('fields: {}'.format(fields))
# 解析出pid
pid = fields[0]
print('pid: {}'.format(pid))
# 以发送信号的形式杀掉进程
os.kill(int(pid), signal.SIGKILL)
print("Process Successfully terminated")
except:
print("Error Encountered while running script")
if __name__ == '__main__':
process()
执行上述代码
(base) xugaoxiang@1070Ti:~/PycharmProjects/pythonProject$ python test.py
Enter process Name: nvidia-smi
line: 16834 pts/1 S+ 0:11 watch -n 1 nvidia-smi
fields: ['16834', 'pts/1', 'S+', '0:11', 'watch', '-n', '1', 'nvidia-smi']
pid: 16834
Process Successfully terminated
在python中启动进程
这里以开启进程,运行 ping -W baidu.com
为例
import os, signal, subprocess, time
def start_process_by_cmd(cmd):
process = subprocess.Popen(cmd, shell=True)
return process.pid
def kill_process_by_pid(pid):
os.kill(pid, signal.SIGKILL)
if __name__ == '__main__':
pid = start_process_by_cmd('ping -W 60 baidu.com')
print('pid: {}'.format(pid))
time.sleep(5)
kill_process_by_pid(pid)
执行代码可以得到输出
pid: 5066
PING baidu.com (39.156.69.79) 56(84) bytes of data.
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=1 ttl=44 time=29.4 ms
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=2 ttl=44 time=29.3 ms
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=3 ttl=44 time=29.8 ms
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=4 ttl=44 time=29.9 ms
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=5 ttl=44 time=29.4 ms