Search code examples
pythonpsutil

How to determine if a process is running in background or foreground using python?


I am doing a project in python in which I want to add a feature like it will kill a background process if it is not running in the foreground. Browsers like firefox and chrome often run in the background after you turn on your computer. I'm using psutil to find the process info and kill it. But in psutil I could not find a way to determine if the process is running in background or foreground. If there is any way to do it using psutil or anything else please let me know.


Solution

  • It can be done using pywin32 library in windows. First you need to install the library. pip install pywin32

    Here's an example on how to use:

    import psutil
    import win32com.client
    
    # Replace 'your_process_name' with the name of the process you want to check
    process_name = 'your_process_name'
    
    # Get a list of running processes
    wmi = win32com.client.GetObject("winmgmts:")
    processes = wmi.InstancesOf("Win32_Process")
    
    for process in processes:
        if process.Name == process_name:
            if process.Status == "Running":
                print(f"{process_name} is running in the foreground.")
            else:
               print(f"{process_name} is running in the background.")