Search code examples
pythonwhile-loopconsoleexe

Not able to run exe containing an infinite while loop as it keeps opening console window even after using pyinstaller to convert and hide the console


I have made a python script which basically has a while loop which waits for a particular exe to start, and as soon as it opens it shuts down the system. But the thing is that the exe file when run, keeps on opening and shutting the console window.

I tried using --noconsole and --windowed as well, but still for a brief moment the console window pops up and disappears, this keeps on repeating, so it's very obvious that there's a background file running.

The alternative might be to not use an infinite loop but I am not able to figure that out.

Here's the code:


def process_exists(process_name):
    call = 'TASKLIST', '/FI', f'imagename eq {process_name}'
    output = subprocess.check_output(call).decode()
    last_line = output.strip().split('\r\n')[-1]
    return last_line.lower().startswith(process_name.lower())

def time ():
    while True:
        if process_exists("RobloxPlayerBeta.exe") or process_exists("RobloxPlayerLauncher.exe"):
            os.system("shutdown /s")
        if process_exists("Windows10Universal.exe"):
            # os.system("shutdown /s") 
            print("Okay")  
        
  
time()

Solution

  • Panav.

    It's not clear how you execute your script, I may guess you do it by simply running it with python.exe. Try using pythonw.exe which doesn't open the console window.

    Another thing to try is building your script in one .exe file and start it as hidden process on startup, you can achieve it like so:

    1. Install PyInstaller and convert the script into a .exe:
    pip install pyinstaller
    pyinstaller --noconsole --onefile YOUR_SCRIPT.py
    

    Converted .exe file will be in .\dist folder named YOUR_SCRIPT.exe.

    Now you can rename the binary file however you want it to be displayed in processes.

    Lastly you have to add your .exe file in startup folder (%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup) to make sure your scripts always active.

    If you want to stop the process, open Processes tab in Task Manager and kill the process by name (YOUR_SCRIPT.exe).

    P.S.: here's a little more clear script doing the same thing:

    import os
    import time
    import subprocess
    
    # List of processes to monitor
    TARGET_PROCESSES = ["RobloxPlayerBeta.exe", "RobloxPlayerLauncher.exe"]
    
    # Function to shut down the computer
    def force_shutdown():
        os.system("shutdown /s /f")
    
    # Function to check if a process is running
    def is_target_process_running():
        try:
            # Get the list of running processes
            output = subprocess.check_output("tasklist", shell=True).decode()
            for process in TARGET_PROCESSES:
                if process in output:
                    return True
        except Exception as e:
            # Ignore errors, e.g., if "tasklist" fails
            print(f"Error: {e}")
        return False
    
    # Main loop to monitor processes
    def monitor_processes():
        while True:
            if is_target_process_running():
                force_shutdown()
                break  # Stop monitoring after shutdown command
            time.sleep(5)  # Check every 5 seconds
    
    
    if __name__ == "__main__":
        monitor_processes()