[Python] .exe file written in python closes , the currently selected app when opening

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I recently created a .exe application using PyInstaller, aiming for it to run seamlessly on my system. My goal was for the app to load a model in the background and remain hidden, running silently in the system tray. This way, the application would stay active without interrupting other tasks or requiring constant interaction.

    To achieve this, I wrote a launcher.py script that acts as an entry point, which then calls the main functionality defined in main.py. I converted launcher.py into an executable using PyInstaller, expecting it to work as intended.

    However, when I run the .exe, it behaves unexpectedly. If I have Windows Explorer selected at the time of launching the app, it causes Windows Explorer to close abruptly. This is not the behavior I expected, as the app should simply load the model and operate quietly in the background without interfering with other processes.

    I’m looking for a solution to ensure that the .exe works smoothly, stays in the system tray, and avoids causing any disruption, like closing Windows Explorer.

    main.py

    import tkinter as tk

    def main():
    # Create the main window
    window = tk.Tk()
    window.title("Hello World App")
    window.geometry("300x200")

    # Create a label with "Hello World" text
    label = tk.Label(window, text="Hello World", font=("Arial", 24))
    label.pack(pady=70)

    # Start the main event loop
    window.mainloop()

    if __name__ == "__main__":
    main()


    launcher.py(for launching main.py)

    import os
    import sys
    import subprocess
    import win32gui
    import win32con
    import win32process
    import logging
    import win32event
    import win32api
    import winerror

    # Setup logging
    logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s: %(message)s',
    handlers=[
    logging.FileHandler('friskocr_launcher.log'),
    logging.StreamHandler()
    ]
    )
    logger = logging.getLogger(__name__)

    def get_application_path():
    """Determine the application's base directory"""
    if getattr(sys, "frozen", False):
    # If running as executable
    console_window = win32gui.GetForegroundWindow()
    win32gui.ShowWindow(console_window, win32con.SW_HIDE)
    return os.path.dirname(sys.executable)
    return os.path.dirname(os.path.abspath(__file__))

    def run_ocr_app():
    """Launch OCR application"""
    try:
    app_dir = get_application_path()
    main_script = os.path.join(app_dir, "main.py")

    if not os.path.exists(main_script):
    logger.error(f"Main script not found: {main_script}")
    sys.exit(1)

    # Create hidden startup configuration
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = win32con.SW_HIDE

    # Launch main application
    subprocess.Popen(
    [sys.executable, main_script], # Using system Python instead of venv
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    startupinfo=startupinfo,
    creationflags=win32process.CREATE_NO_WINDOW,
    )

    logger.info("Application launched successfully")

    except Exception as e:
    logger.error(f"Launcher error: {e}", exc_info=True)
    sys.exit(1)

    if __name__ == "__main__":
    # Mutex to ensure single instance
    mutex_name = "FriskOCR_Mutex"
    mutex = win32event.CreateMutex(None, False, mutex_name)
    if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
    logger.info("Another instance is already running.")
    sys.exit(0)

    run_ocr_app()


    build_exe.py(for converting launcher.py to exe)

    import subprocess
    import sys

    def create_executable():
    pyinstaller_cmd = [
    'pyinstaller',
    '--onefile',
    '--windowed',
    '--name=FriskOCR',
    'launcher.py'
    ]

    try:
    subprocess.check_call(pyinstaller_cmd)
    print("Executable created successfully in 'dist' directory")
    except subprocess.CalledProcessError as e:
    print(f"Error creating executable: {e}")

    if __name__ == '__main__':

    create_executable()

    Continue reading...

Compartilhe esta Página