Convert a Python Script to an Executable (.exe) File

Learn how to convert a Python script to an executable (.exe) file using PyInstaller.

Convert a Python Script to an Executable (.exe) File

Creating an executable file from a Python script can make it easier to distribute and run your application on Windows machines that do not have Python installed. This guide will walk you through the process, including handling common errors you might encounter.

Step 1: Install PyInstaller

First, you need to install PyInstaller. Open your command line interface and run:

pip install pyinstaller

Step 2: Create Your Python Script

Save your Python script (e.g., sum_values.py) that you want to convert to an executable. Here is an example script:

def main():
    try:
        # Ask the user how many numbers they want to sum
        num_values = int(input("Enter the number of values you want to sum: "))
        
        # Initialize an empty list to store the values
        values = []

        # Loop to get the values from the user
        for i in range(num_values):
            value = float(input(f"Enter value {i + 1}: "))
            values.append(value)

        # Calculate the sum of the values
        total_sum = sum(values)

        # Print the sum
        print(f"The sum of the values is: {total_sum}")

    except ValueError:
        print("Invalid input. Please enter numeric values.")

    # Wait for user input before closing
    input("Press Enter to close...")

if __name__ == "__main__":
    main()

Step 3: Use PyInstaller to Create the Executable

Navigate to the directory where your script is located using the command line. Then, run the following command:

pyinstaller --onefile sum_values.py

The --onefile option tells PyInstaller to package everything into a single executable file.

Step 4: Locate the Executable

After running the command, PyInstaller will create several new directories and files. The executable will be located in the dist directory. For example, if your script is named sum_values.py, the executable will be located at dist/sum_values.exe.

Step 5: Run the Executable

You can now distribute the .exe file located in the dist directory. The recipient can run the executable without needing Python installed. 

Handling Common Errors

Error: 'pathlib' package is an obsolete backport

If you encounter an error indicating that the pathlib package is incompatible with PyInstaller, you should create a new Python environment and install only the necessary packages for your script. This ensures your main environment remains unaffected.

Step-by-Step Guide to Handle `pathlib` Issue

  • Create a New Python Environment: If you're using a virtual environment tool like venv, create a new environment:
  • python -m venv pyinstaller_env
  • Activate the New Environment: Activate the newly created environment:
    • On Windows:
    • pyinstaller_env\Scripts\activate
    • On macOS and Linux:
    • source pyinstaller_env/bin/activate
  • Install Required Packages: Install PyInstaller and any other required packages (e.g., pywin32 and pywin32-ctypes):
  • pip install pyinstaller pywin32 pywin32-ctypes
  • Verify Package Installation: Ensure you can import the necessary packages:
  • python -c "import pywintypes; import win32api"
  • Convert Your Python Script to an Executable: Navigate to the directory containing your script (sum_values.py) and run PyInstaller:
  • pyinstaller --onefile sum_values.py
  • Locate the Executable: The executable will be in the dist directory. You can find it at dist/sum_values.exe.
  • Deactivate the Environment: After you're done, you can deactivate the environment:
  • deactivate

Error: Could not import 'pywintypes' or 'win32api' from 'win32ctypes.pywin32'

If you encounter issues related to pywintypes or win32api, follow these steps:

  • Ensure `pywin32` is Installed:
  • pip install pywin32
  • Reinstall `pywin32-ctypes`:
  • pip uninstall pywin32-ctypes
    pip install pywin32-ctypes
  • Run the `pywin32` Post-Install Script:
  • python -m pywin32_postinstall
  • Verify the Installation: Open a Python shell and ensure you can import the necessary packages without errors:
  • import pywintypes
    import win32api
  • Retry PyInstaller:
  • pyinstaller --onefile sum_values.py

By following these steps and handling common errors, you can successfully convert your Python script to an executable file and ensure it runs smoothly on Windows machines without Python installed.