[英]How to check if a process is running in Python?
我正在做一个阻止某些应用程序打开的程序。 但是它占用大量CPU。 因为程序总是试图终止该应用程序。 我希望该程序使用更少的CPU。 我怎样才能做到这一点?
附言 : 我2个小时无法达到这个结果。
我的Python版本: 3.6.3
我不需要任何第三方模块。
我的代码占用大量CPU:
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
while True:
subprocess.call("taskkill /F /IM chrome.exe", startupinfo=si)
subprocess.call("taskkill /F /IM opera.exe", startupinfo=si)
subprocess.call("taskkill /F /IM iexplore.exe", startupinfo=si)
subprocess.call("taskkill /F /IM firefox.exe", startupinfo=si)
sleep(1)
如果您坚持不使用任何第三方模块(并且我认为在Windows上运行时win32api仍应随Python一起提供),则至少可以将大部分工作转移给使用Win32 API的系统,而不是尝试做所有事情通过Python。 这是我的处理方式:
import subprocess
import time
# list of processes to auto-kill
kill_list = ["chrome.exe", "opera.exe", "iexplore.exe", "firefox.exe"]
# WMI command to search & destroy the processes
wmi_command = "wmic process where \"{}\" delete\r\n".format(
" OR ".join("Name='{}'".format(e) for e in kill_list))
# run a single subprocess with Windows Command Prompt
proc = subprocess.Popen(["cmd.exe"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
while True:
proc.stdin.write(wmi_command.encode("ascii")) # issue the WMI command to it
proc.stdin.flush() # flush the STDIN buffer
time.sleep(1) # let it breathe a little
在大多数情况下,您甚至都不会注意到这一性能的影响。
现在,为什么首先需要这样的东西是一个完全不同的话题-我认为这样的脚本在现实世界中没有用途。
也许使用psutil更快:
import psutil
for process in psutil.process_iter():
if process.name() == 'myprocess':
process.kill()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.