Issue Running Streamlit .exe File on Non-Python Installed PCs

Hello everyone,

I hope someone can assist me with this issue.

I have a main.py script that runs the entire program locally. I’ve used PyInstaller along with additional hooks, hidden imports, and the collect command for all necessary libraries to create an .exe file.

import os
import sys
import subprocess
import logging
import traceback


def setup_logging():
    """
    Set up the logging system to record errors and information in a log file next to the executable.
    """
    try:
        if getattr(sys, 'frozen', False):
            # If the program is frozen using PyInstaller
            base_path = sys._MEIPASS
            executable_path = os.path.dirname(sys.executable)
        else:
            # If the program is running from the source
            base_path = os.path.dirname(os.path.abspath(__file__))
            executable_path = base_path

        # Path to the log file
        log_file = os.path.join(executable_path, 'streamlit_app.log')

        # Set up the logging system
        logging.basicConfig(
            level=logging.DEBUG,  # Logging level
            format='%(asctime)s | %(levelname)s | %(message)s',
            handlers=[
                logging.FileHandler(log_file, mode='a', encoding='utf-8'),
                logging.StreamHandler(sys.stdout)  # To display logs in the console
            ]
        )

        logging.debug("Logging system successfully initialized.")
        return base_path, log_file

    except Exception as e:
        # In case of logging setup failure
        print(f"Failed to set up logging system: {e}")
        sys.exit(1)


def run_streamlit(ui_path):
    """
    Run the Streamlit application as a subprocess and log any errors that occur.
    """
    try:
        logging.info(f"Starting Streamlit application from path: {ui_path}")

        # Run Streamlit as a subprocess
        process = subprocess.Popen(
            ['streamlit', 'run', ui_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False  # It is preferable to avoid using shell=True for security reasons
        )

        # Read the process outputs
        stdout, stderr = process.communicate()

        # Log stdout output
        if stdout:
            logging.info(f"Streamlit Output:\n{stdout.decode('utf-8')}")

        # Log stderr output
        if stderr:
            logging.error(f"Streamlit Errors:\n{stderr.decode('utf-8')}")

        # Check the process exit code
        if process.returncode != 0:
            logging.error(f"Streamlit exited with error. Exit code: {process.returncode}")
            sys.exit(process.returncode)
        else:
            logging.info("Streamlit exited successfully.")

    except FileNotFoundError:
        logging.error("Streamlit is not installed or not available in the environment path.")
        sys.exit(1)
    except Exception as e:
        logging.error(f"An unexpected error occurred while running Streamlit: {e}")
        logging.error(traceback.format_exc())
        sys.exit(1)


def main():
    """
    The main function to run the program.
    """
    try:
        base_path, log_file = setup_logging()
        logging.info("Program execution started.")

        ui_path = os.path.join(base_path, 'ui.py')

        # Check if ui.py exists
        if not os.path.exists(ui_path):
            logging.error(f"ui.py file not found at path: {ui_path}")
            print(f"Error: ui.py not found at {ui_path}. Please check the log file for more details.")
            sys.exit(1)
        else:
            logging.debug("ui.py file found successfully.")

        # Change the current directory to the base path
        os.chdir(base_path)
        logging.debug(f"Current working directory changed to: {base_path}")

        # Run the Streamlit application
        run_streamlit(ui_path)

    except Exception as e:
        logging.critical(f"A critical error occurred during program execution: {e}")
        logging.critical(traceback.format_exc())
        print(f"Fatal error occurred. Check the log file for details: {log_file}")
        sys.exit(1)
    finally:
        logging.info("Program execution finished.")


if __name__ == '__main__':
    main()

The .exe file works perfectly on my PC. However, when I try to open the .exe file on a PC that does not have Python or Streamlit installed, it fails to open.

Any assistance with resolving this issue would be greatly appreciated.