简体   繁体   中英

How can i kill background python processes?

I want the python syntax that will give me the list of background processes running through python itself, and kill all those processes at a time. what modification should I do in my following code?

I have written this code to get all the running processes and kill the specific one by its name.

import psutil

for proc in psutil.process_iter():
    try:
        # Get process name & pid from process object.
        processName = proc.name()
        processID = proc.pid
        print(processName , ' ::: ', processID)
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass

for proc in psutil.process_iter():
    if proc.name() == "powershell.exe":
        proc.kill()

You should be able to kill python processes with the exact same approach. Of course: Be careful! If I would do this on my machine, I would kill some processes that are doing important work for me:)

Find out how your python interpreter is called. I assume it is 'python3.exe' or 'python.exe'. On my machine it is 'python3'.

Be careful that your python script does not kill itself. For that you can check what the pid of the killer script is. The following example works for me. I have replaced the proc.kill() statement with a print for obvious reasons.

import psutil
import os

my_pid = os.getpid()

for proc in psutil.process_iter():
    try:
        # Get process name & pid from process object.
        processName = proc.name()
        processID = proc.pid

        if proc.pid == my_pid:
            print("I am not suicidal")
            continue

        if processName.startswith("python3"): # adapt this line to your needs
            print(f"I will kill {processName}[{processID}] : {''.join(proc.cmdline())})")
            # proc.kill()
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
        print(e)

Output:

I will kill python3[11205] : python3-cimport time; time.sleep(1000))
I am not suicidal
I will kill python3[15745] : <another python job running on my machine>

The Python process that just does time.sleep was started by me for testing purposes in advance.

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