import subprocess
class Process_Manager:
def __init__(self, process_name, log_name):
self.process_name = process_name
self.log_name = log_name
def check(self):
pids = self._get_pids()
if len(pids) < 2:
print(f"进程 {self.process_name} 不存在, 尝试重新拉起...")
self.start()
return
elif len(pids) > 2:
print(f"进程 {self.process_name} 异常...")
print("进程运行中, ID:", pids[0])
def restart(self):
pids = self._get_pids()
self.kill(pids)
self.start()
def start(self):
command = f"nohup python {self.process_name} > {self.log_name} 2>&1 &"
subprocess.call(command, shell=True)
def kill(self, pids=None):
if pids is None:
pids = self._get_pids()
print("退出进程!!")
for p in pids[:-1]:
command = f"kill {p}"
subprocess.call(command, shell=True)
print(command)
def _get_pids(self):
command = f"pgrep -f 'python {self.process_name}'"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, _ = process.communicate()
pids = output.decode().split("\n")[:-1]
return pids