监测进程是否在运行
最近项目中需要去判断进程爬虫是否正在运行,本来使用win32com,但是发现在被django view.py中调用的时候居然总是提示‘Invalid syntax’,后来换用psutil就能正常运行。并且psutil是跨平台的。
一、使用win32com来判断进程是否存在
import os import win32com.client def proc_exist(process_name): is_exist = False wmi = win32com.client.GetObject('winmgmts:') processCodeCov = wmi.ExecQuery('select * from Win32_Process where name=\"%s\"' %(process_name)) if len(processCodeCov) > 0: is_exist = True return is_exist if proc_exist('SuZhouNewWeb.exe'): print('SuZhouNewWeb.exe is running') else: os.system('') print('no such process...')
二、使用psutil来判断
# 使用psutil来判断 import time import win32api import psutil def proc_exist(process_name): pl = psutil.pids() for pid in pl: if psutil.Process(pid).name() == process_name: return pid if __name__ == '__main__': while True: if isinstance(proc_exist('SuZhouNewWeb.exe'), int): print('SuZhouNewWeb.exe is running') else: print('no such process...') win32api.ShellExecute(0, 'open', r'D:\demo\reptile_demo\爬虫\SuZhouNewWeb.exe', '', '', 1) print('Process startup') time.sleep(300) ##每隔5分钟进行检查

浙公网安备 33010602011771号