'Why can't I create an executable from my Python script?

I tried to convert my Python script CHAP.py into an executable with py2exe in Python 3.10. This is what happens:


C:\Users\MiDy1\source\repos\CHAP_2> python setup.py py2exe
C:\Users\MiDy1\source\repos\CHAP_2\setup.py:1: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
  from distutils.core import setup
running py2exe

  58 missing Modules
  ------------------
? IPython.display                     imported from PIL.ImageShow
? PIL._imagingagg                     imported from -
? PyQt5.QtCore                        imported from PIL.ImageQt
? PyQt5.QtGui                         imported from PIL.ImageQt
? PyQt6.QtCore                        imported from PIL.ImageQt
? PyQt6.QtGui                         imported from PIL.ImageQt
? PySide2.QtCore                      imported from PIL.ImageQt
? PySide2.QtGui                       imported from PIL.ImageQt
? PySide6.QtCore                      imported from PIL.ImageQt
? PySide6.QtGui                       imported from PIL.ImageQt
? __builtin__                         imported from pkg_resources._vendor.pyparsing
? __main__                            imported from bdb, pdb, pkg_resources
? _ast_gen                            imported from pycparser._build_tables
? _dummy_thread                       imported from cffi.lock
? _frozen_importlib                   imported from importlib, importlib.abc, zipimport
? _frozen_importlib_external          imported from importlib, importlib._bootstrap, importlib.abc, zipimport
? _manylinux                          imported from pkg_resources._vendor.packaging.tags
? _posixshmem                         imported from multiprocessing.resource_tracker, multiprocessing.shared_memory
? _winreg                             imported from pkg_resources._vendor.appdirs, platform
? asyncio.DefaultEventLoopPolicy      imported from -
? cPickle                             imported from pycparser.ply.yacc
? cStringIO                           imported from cffi.ffiplatform
? c_ast                               imported from pycparser._build_tables
? cffi._pycparser                     imported from -
? collections.Callable                imported from cffi.api
? collections.Iterable                imported from pkg_resources._vendor.pyparsing
? collections.MutableMapping          imported from pkg_resources._vendor.pyparsing
? com.sun                             imported from pkg_resources._vendor.appdirs
? com.sun.jna                         imported from pkg_resources._vendor.appdirs
? com.sun.jna.platform                imported from pkg_resources._vendor.appdirs
? defusedxml.ElementTree              imported from PIL.Image
? dummy.Process                       imported from multiprocessing.pool
? dummy_thread                        imported from cffi.lock
? java.lang                           imported from platform
? lextab                              imported from pycparser._build_tables
? numpy                               imported from PIL.Image, PIL.ImageFilter
? olefile                             imported from PIL.FpxImagePlugin, PIL.MicImagePlugin
? ordereddict                         imported from pkg_resources._vendor.pyparsing
? org.python.core                     imported from copy, pickle
? os.path                             imported from cffi.ffiplatform, ctypes._aix, distutils.file_util, os, pkg_resources, pkgutil, py_compile, pycparser.ply.yacc, sysconfig, tracemalloc, unittest, unittest.util
? packaging.version                   imported from PIL.ImageFont
? pep517                              imported from importlib.metadata
? pkg_resources.extern.appdirs        imported from pkg_resources
? pkg_resources.extern.packaging      imported from pkg_resources
? pkg_resources.extern.pyparsing      imported from pkg_resources._vendor.packaging.markers, pkg_resources._vendor.packaging.requirements
? readline                            imported from cmd, code, pdb
? resource                            imported from test.support
? setuptools.extern.more_itertools    imported from setuptools.dist
? setuptools.extern.ordered_set       imported from setuptools.dist
? setuptools.extern.packaging         imported from setuptools.command.egg_info, setuptools.dist
? setuptools.extern.packaging.specifiers imported from setuptools.config
? setuptools.extern.packaging.tags    imported from setuptools.wheel
? setuptools.extern.packaging.utils   imported from setuptools.wheel
? setuptools.extern.packaging.version imported from setuptools.config
? thread                              imported from cffi.cparser, cffi.lock
? win32api                            imported from pkg_resources._vendor.appdirs
? win32com.shell                      imported from pkg_resources._vendor.appdirs
? yacctab                             imported from pycparser._build_tables
Building 'dist\CHAP.exe'.
Building shared code archive 'dist\library.zip'.
Copy c:\users\midy1\appdata\local\programs\python\python310\python310.dll to dist
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\select.pyd to dist\select.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_bz2.pyd to dist\_bz2.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_lzma.pyd to dist\_lzma.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\unicodedata.pyd to dist\unicodedata.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_hashlib.pyd to dist\_hashlib.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_decimal.pyd to dist\_decimal.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_socket.pyd to dist\_socket.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\pyexpat.pyd to dist\pyexpat.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_ssl.pyd to dist\_ssl.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_queue.pyd to dist\_queue.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_elementtree.pyd to dist\_elementtree.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_testcapi.pyd to dist\_testcapi.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_ctypes.pyd to dist\_ctypes.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_tkinter.pyd to dist\_tkinter.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_testinternalcapi.pyd to dist\_testinternalcapi.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_asyncio.pyd to dist\_asyncio.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_multiprocessing.pyd to dist\_multiprocessing.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_overlapped.pyd to dist\_overlapped.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\_uuid.pyd to dist\_uuid.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imaging.cp310-win_amd64.pyd to dist\PIL._imaging.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\_cffi_backend.cp310-win_amd64.pyd to dist\_cffi_backend.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imagingtk.cp310-win_amd64.pyd to dist\PIL._imagingtk.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imagingcms.cp310-win_amd64.pyd to dist\PIL._imagingcms.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imagingft.cp310-win_amd64.pyd to dist\PIL._imagingft.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imagingmath.cp310-win_amd64.pyd to dist\PIL._imagingmath.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_imagingmorph.cp310-win_amd64.pyd to dist\PIL._imagingmorph.pyd
Copy C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\lib\site-packages\PIL\_webp.cp310-win_amd64.pyd to dist\PIL._webp.pyd
Copy DLL C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\tcl86t.dll to dist\
Copy DLL C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\libcrypto-1_1.dll to dist\
Copy DLL C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\tk86t.dll to dist\
Copy DLL C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\libssl-1_1.dll to dist\
Copy DLL C:\Users\MiDy1\AppData\Local\Programs\Python\Python310\DLLs\libffi-7.dll to dist\

Then I wanted to start my executable and got this error:


PS C:\Users\MiDy1\source\repos\CHAP_2> cd .\dist\
PS C:\Users\MiDy1\source\repos\CHAP_2\dist> .\CHAP.exe
Traceback (most recent call last):
  File "CHAP.py", line 4, in <module>
  File "PySimpleGUI\__init__.pyc", line 2, in <module>
  File "PySimpleGUI\PySimpleGUI.pyc", line 178, in <module>
ModuleNotFoundError: No module named 'site'

Does anyone know where this is coming from? Maybe I didn't install some packages or anything? I would be very grateful if you could help me out here.

Here's my CHAP.py:


# CHAP.py
import glob
import time
import PySimpleGUI as sg
from PIL import Image, ImageTk
import ctypes


#reference white in LAB
whitepoint_L = 100
whitepoint_A = 2.6249468183253133
whitepoint_B = -1.8752341146301976

#gradient_border determines how harsh the picture is treated
gradient_border = 100

#Debug on (1) or Debug off(0)
debug_LAB = 0       
debug_dist = 0      
debug_RGB = 0       
debug_gf = 0       

#screensize and image dimensions
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
window_width = screensize/4*3
window_height = window_width/16*9
image_dim = window_width/2


def search_images(path):
    images = glob.glob(f'{path}/*.jpg') + glob.glob(f'{path}/*.png')
    return images

def load_image(path, window):

    start_time = time.time()

    try:
        original_image = Image.open(path)
        original_image.thumbnail((image_dim, image_dim))
        photo_img1 = ImageTk.PhotoImage(original_image)
        
        window["original_picture"].update(data=photo_img1)
    except:
        print(f"Couldnt open {path}!")
        return -1

    try:
        width = original_image.size[0]
        height = original_image.size[1]
        ergebnis_image = Image.new('RGB', (width, height), color = 'red')

        original_pixels = original_image.load()
        ergebnis_pixels = ergebnis_image.load()

        for x in range(0,width):
            for y in range(0, height):
                original_R, original_G, original_B = original_pixels[x, y]
                ergebnis_R, ergebnis_G, ergebnis_B = get_resulting_RGB(original_R, original_G, original_B)
                ergebnis_pixels[x, y] = (ergebnis_R, ergebnis_G, ergebnis_B)

        photo_img2 = ImageTk.PhotoImage(ergebnis_image)
        window["resulting_picture"].update(data=photo_img2)
    except:
        print(f"Couldnt create resulting picture!")
        return -1



    stop_time = time.time()
    delta_time = stop_time - start_time
    print(f"time passed: ", float("{:.03f}".format(delta_time)), "[s]")
    return 0
        
def get_resulting_RGB(original_R, original_G, original_B):

    if original_R < 25 and original_G < 25 and original_B < 25:
        return 0, 0, 0

    L, A, B = RGB_to_LAB(original_R, original_G, original_B)
    if debug_LAB: print("LAB: ", L, A, B)

    distance = calc_distance_in_LAB(L, A, B)
    if debug_dist: print("Distance: ", distance)

    resulting_R, resulting_G, resulting_B = get_gradient_color(distance)
    if debug_RGB: print("R: ", resulting_R, " / G: ", resulting_G, " / B: ", resulting_B)

    return resulting_R, resulting_G, resulting_B

def RGB_to_LAB(original_R, original_G, original_B):

    #normalize RGB
    original_R /= 255
    original_G /= 255
    original_B /= 255

    #linearize RGB
    original_R = linearize_RGB(original_R)
    original_G = linearize_RGB(original_G)
    original_B = linearize_RGB(original_B)

    #calculate XYZ
    X = (0.4124564 * original_R) + (0.3575761 * original_G) + (0.1804375 * original_B)
    Y = (0.2126729 * original_R) + (0.7151522 * original_G) + (0.072175 * original_B)
    Z = (0.0193339 * original_R) + (0.119192 * original_G) + (0.9503041 * original_B)

    #linearize XYZ
    X *= 100
    Y *= 100
    Z *= 100

    #reference whitepoint in XYZ
    ref_X = 95.05
    ref_Y = 100
    ref_Z = 108.899999

    #calculate t's
    t_X = X/ref_X
    t_Y = Y/ref_Y
    t_Z = Z/ref_Z

    #get functions
    f_X = which_f(t_X)
    f_Y = which_f(t_Y)
    f_Z = which_f(t_Z)

    #calculate LAB-coordinates
    L = (116 * f_Y) - 16
    A = 500 * (f_X - f_Y)
    B = 200 * (f_Y - f_Z)

    #return
    return L, A, B

def linearize_RGB(single_RGB):
    if(single_RGB <= 0.04045):
        linearized_RGB = single_RGB/12.92;
    else:
        linearized_RGB = pow((single_RGB + 0.055)/1.055, 2.4)

    return linearized_RGB

def which_f(t):
    #constants
    epsilon = 216/24389
    kappa = 24389/27

    #check which operation is necessary
    if t > epsilon:
        f = pow(t, 1/3)
    else:
        f = ((kappa*t)+16)/116
    
    return f

def calc_distance_in_LAB(L, A, B):
    delta_L = L - whitepoint_L
    delta_L_squared = pow(delta_L, 2)
    
    delta_A = A - whitepoint_A
    delta_A_squared = pow(delta_A, 2)
    
    delta_B = B - whitepoint_B
    delta_B_squared = pow(delta_B, 2)

    root_term = delta_L_squared + delta_A_squared + delta_B_squared

    distance = pow(root_term, 0.5)

    return distance

def get_gradient_color(distance):

    g_factor = float(distance / gradient_border)
    if debug_gf: print("gradient factor: ", g_factor)

    if distance > gradient_border:
        gradient_R = 255 
        gradient_G = 0
        gradient_B = 0

    elif g_factor < 0.5:
        gradient_R = int(255 * (g_factor / 0.5))
        gradient_G = 255
        gradient_B = 0

    elif g_factor >= 0.5:
        gradient_R = 255
        gradient_G = 255 - int(255 * ((g_factor - 0.5) / 0.5))
        gradient_B = 0

    return gradient_R, gradient_G, gradient_B

def main():
    elements = [
        [sg.Image(key="original_picture"), sg.Image(key="resulting_picture")],
        [
            sg.Text("Image folder: "),
            sg.Input(size=(25, 1), enable_events=True, key="folder"),
            sg.FolderBrowse(),
        ],
        [
            sg.Button("prev"),
            sg.Button("next")
        ]
    ]

    window = sg.Window(title="CHAP", layout=elements, size=(window_width, window_height), element_justification='c')
    images = []
    location = 0

    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break

        if event == "folder":
            images = search_images(values["folder"])
            if images:
                load_image(images[0], window)
                location = 0

        if event == "next" and images:
            if location == len(images) - 1:
                location = 0
            else:
                location += 1
            load_image(images[location], window)

        if event == "prev" and images:
            if location == 0:
                location = len(images) - 1
            else:
                location -= 1
            load_image(images[location], window)

    window.close()

if __name__ == "__main__":
    main()

screenshot 1

screenshot 2



Solution 1:[1]

Not sure how py2exe work and the execution file won't not find the site.py which come with Python. This module is automatically imported during initialization.

The only way I known is to remark the line import site from your Lib\site-packages\PySimpleGUIPySimpleGUI.py, then it will be fine.

revise line from

import os
import sys
import re
import site
import tempfile
import ctypes
import platform

to

import os
import sys
import re
#import site
import tempfile
import ctypes
import platform

Note: After you remarked import site, you can not use the method provided by PySimpleGUI to upgrade from github. Of course, it will be fine after you remove the remark.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1