[英]How to Keep terminating a program using a Windows Service in Python?
I have a Python Script that creates a Windows Service and checks whether Powershell is running using psutil
.我有一个 Python 脚本,它创建一个 Windows 服务并使用
psutil
检查 Powershell 是否正在运行。 However there is an issue in the code that I can't figure out.但是代码中有一个我无法弄清楚的问题。
Either the Service starts and stops immediately ( like in the current state ) or it starts but does not terminate the program.服务要么立即启动和停止(如在当前状态下),要么启动但不终止程序。 ( if for example
else: break
is changed to else: continue
) (例如
else: break
改为else: continue
)
I want the service to run indefinitely (until a service stop command is issued ) and constantly check whether powershell.exe has been started and terminate it.我希望服务无限期地运行(直到发出服务停止命令)并不断检查 powershell.exe 是否已启动并终止它。
I also wanted to expand to if 'powershell' or 'powershell_ise' in (p.name() for p in psutil.process_iter()):
but that for some reason is always True
even if powershell is not started.我还想扩展为
if 'powershell' or 'powershell_ise' in (p.name() for p in psutil.process_iter()):
但由于某种原因,即使 powershell 未启动,它也始终为True
。
Here is the part of the code that is relevant:这是相关的代码部分:
def SvcDoRun(self):
while True:
result = win32event.WaitForSingleObject(self._stop_event, 1000)
if result == win32event.WAIT_OBJECT_0:
break
else:
if 'powershell' in (p.name() for p in psutil.process_iter()):
os.system("taskkill /f /t /im powershell.exe")
else:
break
Break in the else would mean, that if there is no powershell process, you would end the service.中断 else 意味着,如果没有 powershell 进程,您将结束服务。 I don't think that is what you intend.
我不认为那是你想要的。 Either there should be a continue or no else block altogether.
要么应该有一个 continue 要么完全没有 else 块。
the condition条件
if 'powershell' or 'powershell_ise' in (p.name() for p in psutil.process_iter()):
is always True, because bool('powershell)
is always True and the operator precedence is as始终为 True,因为
bool('powershell)
始终为 True 且运算符优先级为
if 'powershell' or ('powershell_ise' in ['notepad']):
You can use set intersection您可以使用设置交集
if {'powershell', 'powershell_ise'} & set(psutils.process_iter()):
You could try psutil.kill:你可以试试 psutil.kill:
for proc in psutil.process_iter():
if proc.name() in ('powershell', 'powershell_ise'):
proc.kill()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.