import subprocess import sys import os import psutil from pathlib import Path def stop_scheduler(): """停止定时任务进程""" stopped_count = 0 try: # 方法1: 使用psutil精确查找进程 current_dir = str(Path(__file__).parent) for proc in psutil.process_iter(['pid', 'name', 'cmdline']): try: if proc.info['name'] in ['python.exe', 'pythonw.exe']: cmdline = proc.info['cmdline'] if cmdline and len(cmdline) > 1: # 检查是否是我们的scheduler.py进程 if 'scheduler.py' in ' '.join(cmdline) and current_dir in ' '.join(cmdline): print(f"找到进程: PID={proc.info['pid']}, 命令行={' '.join(cmdline)}") proc.terminate() proc.wait(timeout=5) # 等待进程正常结束 print(f"已终止进程 PID={proc.info['pid']}") stopped_count += 1 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): continue except ImportError: print("psutil模块未安装,使用备用方法...") # 方法2: 备用方法 - 改进的tasklist方式 try: # 获取详细的进程信息 result = subprocess.run(['wmic', 'process', 'where', 'name="pythonw.exe"', 'get', 'ProcessId,CommandLine', '/format:csv'], capture_output=True, text=True, encoding='gbk') lines = result.stdout.strip().split('\n') current_dir = str(Path(__file__).parent) for line in lines[1:]: # 跳过标题行 if line.strip() and 'scheduler.py' in line and current_dir in line: # 提取PID parts = line.split(',') if len(parts) >= 2: pid = parts[-1].strip() if pid.isdigit(): subprocess.run(['taskkill', '/F', '/PID', pid], check=True) print(f"已终止进程 PID={pid}") stopped_count += 1 except subprocess.CalledProcessError as e: print(f"备用方法执行失败: {e}") # 方法3: 最后的备用方案 try: result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq pythonw.exe', '/FO', 'CSV'], capture_output=True, text=True) if 'pythonw.exe' in result.stdout: print("警告: 找到pythonw.exe进程,但无法确定是否为目标进程") response = input("是否强制结束所有pythonw.exe进程?(y/N): ") if response.lower() == 'y': subprocess.run(['taskkill', '/F', '/IM', 'pythonw.exe'], check=True) print("已强制结束所有pythonw.exe进程") stopped_count += 1 except subprocess.CalledProcessError as e: print(f"最后备用方案失败: {e}") if stopped_count > 0: print(f"成功停止了 {stopped_count} 个定时任务进程") else: print("未找到运行中的定时任务进程") # 额外检查:查看是否还有相关进程 print("\n检查剩余进程...") try: result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq pythonw.exe'], capture_output=True, text=True) if 'pythonw.exe' in result.stdout: print("仍有pythonw.exe进程在运行:") print(result.stdout) else: print("没有发现pythonw.exe进程") except: pass if __name__ == "__main__": stop_scheduler()