You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Windows服务持续终止PowerShell进程的代码问题排查

问题排查与修复方案

你的代码一共有3处逻辑错误,对应所有异常现象:

  • 服务启动即停止的原因:内层else: break逻辑错误——当轮询周期内没检测到PowerShell进程时,直接执行break跳出了服务运行的主while循环,SvcDoRun函数直接返回,服务进程自然终止。
  • 改成else: continue后无法终止进程的原因:进程名匹配逻辑错误。psutil.Process.name()返回的Windows进程名是带.exe后缀的完整名称,即powershell.exe、powershell_ise.exe,用不带后缀的'powershell'做匹配永远无法命中目标进程,自然不会触发终止逻辑。
  • 多进程匹配条件永远为True的原因:Python逻辑运算符优先级问题。if 'powershell' or 'powershell_ise' in 进程列表会被解析为if ('powershell' 布尔值为真) or ('powershell_ise' in 进程列表),非空字符串的布尔值恒为True,因此整个判断条件永远成立,和进程列表实际内容无关。

修正后可运行代码
import psutil
import os
import win32event
# 原有服务依赖的其他导入保持不变

def SvcDoRun(self):
    while True:
        # 每1秒检查一次服务停止信号,不阻塞进程检测逻辑
        result = win32event.WaitForSingleObject(self._stop_event, 1000)
        # 仅在收到服务停止指令时才退出主循环
        if result == win32event.WAIT_OBJECT_0:
            break
        
        # 拉取当前所有运行进程的名称,统一转小写避免大小写匹配问题
        running_process = [p.name().lower() for p in psutil.process_iter()]
        # 匹配并终止目标进程
        if 'powershell.exe' in running_process:
            os.system("taskkill /f /t /im powershell.exe")
        if 'powershell_ise.exe' in running_process:
            os.system("taskkill /f /t /im powershell_ise.exe")

优化提示:如果不想调用系统taskkill命令,也可以直接用psutil自带的进程终止能力,遍历进程时判断到目标进程直接调用p.kill()即可,执行效率比调用外部命令更高。


内容的提问来源于stack exchange,提问作者John Linaer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 16:06:23