-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocess_manager.py
More file actions
89 lines (78 loc) · 1.98 KB
/
process_manager.py
File metadata and controls
89 lines (78 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
进程相关处理
"""
import os
import time
import psutil
def kill_pid(pid):
"""
中止传入pid所对应的进程
:param pid: 进程id
:return:
"""
if os.name == 'nt':
# Windows系统
cmd = 'taskkill /pid ' + str(pid) + ' /f'
try:
os.system(cmd)
print(pid, 'killed')
except Exception as e:
print(e)
elif os.name == 'posix':
# Linux系统
cmd = 'kill ' + str(pid)
try:
os.system(cmd)
print(pid, 'killed')
except Exception as e:
print(e)
else:
print('Undefined os.name')
def write_current_pid(filepath='default.pid'):
"""
将当前程序的经常id写入文件
:return:
"""
with open(filepath, mode='w') as fin:
fin.write(os.getpid().__str__())
def read_pid_from_file(filepath='default.pid'):
"""
从pid文件中读取进程id
:param filepath:
:return:
"""
with open(filepath, mode='r') as fout:
return fout.read()
def get_pid_from_process(proc_name):
"""
便利进程列表,获取指定名称的进程id
:return:
"""
for proc in psutil.process_iter():
try:
if proc.name() == proc_name:
return proc.pid
except psutil.NoSuchProcess:
pass
return None
def restart_exe_process(proc_name):
"""
管理某个进程,定时自动重启
:param proc_name:
:return:
"""
time_counter = 0
os.system(f'start {proc_name}.exe')
print(f'start process: {proc_name}.exe')
while True:
time_counter += 1
time.sleep(1)
if time_counter == 1800:
print('time counter attach.')
pid = read_pid_from_file(f'{proc_name}.pid')
kill_pid(pid)
print(f'kill pid: {pid}')
time.sleep(1)
os.system(f'start {proc_name}.exe')
print(f'restart {proc_name}.exe')
time_counter = 0