简体   繁体   中英

How to check if a process is running in Python?

I am doing a program that prevents certain applications from opening. But it uses a lot of CPU. Because the program is always trying to terminate that application. I want this program to use less of the CPU. How can I do this?

PS : I could not reach this result for 2 hours.

My Python Version : 3.6.3

I don't want any 3rd party modules.

My code that uses a lot of 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)

If you insist on no 3rd party modules (and I'd argue that win32api when running on Windows should be shipped with Python anyway), you can at least offset most of the work to systems that do utilize Win32 API instead of trying to do everything through Python. Here's how I'd do it:

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

In most cases you won't even notice the performance impact of this one.

Now, why would you need such a thing in the first place is a completely different topic - I'd argue that there is no real-world use for a script like this.

Maybe it is faster to use psutil:

import psutil

for process in psutil.process_iter():
    if process.name() == 'myprocess':
        process.kill()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM