Related
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()
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.
I want to list my input devices on my windows (like microphone and etc.).
the code is here :
from ctypes import *
import sys
#printf = libc.printf
winmm = windll.LoadLibrary("winmm.dll")
widn = winmm.waveInGetDevCapsA #wave in device num
widn.restype = c_uint
waveNum = winmm.waveInGetNumDevs
class LPWAVEINCAPS(Structure):
_fields_ = [
("wMid",c_ushort),
("wPid",c_ushort),
("vDriverVersion",c_uint),
("szPname",c_wchar_p),
("dwFormats",c_uint),
("wChannels",c_ushort),
("wReserved1",c_ushort),
]
widn.argtypes = [
c_uint,
POINTER(LPWAVEINCAPS),
c_uint
]
count_devs = waveNum()
print(count_devs)
structLP = LPWAVEINCAPS()
for i in range(count_devs):
str = widn(c_uint(i),byref(structLP),c_uint(sys.getsizeof(structLP)))
print(structLP.szPname)
The output is Segment fault and when I remove byref it gave me None as output.
help me please thank you so much :)
Iā solved the problem :ā
the problem was my string pointer, Iā used s = create_string_buffer(b'\000' * 32) and then ("szPname", type(s)) in the structure
from ctypes import *
import sys
#printf = libc.printf
winmm = windll.LoadLibrary("winmm.dll")
widn = winmm.waveInGetDevCapsA #wave in device num
widn.restype = c_uint
waveNum = winmm.waveInGetNumDevs
s = create_string_buffer(b'\000' * 32)
class LPWAVEINCAPS(Structure):
_fields_ = [
("wMid",c_ushort),
("wPid",c_ushort),
("vDriverVersion",c_uint),
("szPname", type(s)),
("dwFormats",c_uint),
("wChannels",c_ushort),
("wReserved1",c_ushort),
]
widn.argtypes = [
c_uint,
POINTER(LPWAVEINCAPS),
c_uint
]
count_devs = waveNum()
print(count_devs)
structLP = LPWAVEINCAPS()
for i in range(count_devs):
print(sizeof(type(structLP)))
str = widn(c_uint(i),byref(structLP),sizeof(structLP))
print(structLP.szPname)
#waveCaps = winmm.waveOutGetDevCaps
waveNum.restype = c_uint
#waveCaps.argtypes = []
I am facing asimilar problem as described here and used the answer given in the post.
I am using Python 2.7 on Windows 64 bit machine and using ctypes that comes as default with Python. Given code in above link.
pyfrom ctypes import *
pycrt = cdll.msvcrt
py_sopen = crt._sopen
py_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
py_SH_DENYRW = 0x10 # from <share.h>
pyh = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0)
print pyh
pyfrom ctypes import *
^
SyntaxError: invalid syntax
If I change pyfrom ctypes import * to from ctypes import * then py_sopen = crt._sopen
NameError: name 'crt' is not defined
pyfrom ctypes import * is not a valid syntax. It should be from ctypes import *
whoever gave you that code messed. Remove py from the start of every variable name and it atleast runs, i can't tell you if it does what you expect though.
from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0)
print h
testing functionality:
filename = r"C:\python\test.txt"
f = open(filename, 'w')
from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen(filename, 0, _SH_DENYRW, 0)
print h
f.close()
from ctypes import *
crt = cdll.msvcrt
_sopen = crt._sopen
_sopen.argtypes = (c_char_p, c_int, c_int, c_int)
_SH_DENYRW = 0x10 # from <share.h>
h = _sopen(filename, 0, _SH_DENYRW, 0)
print h
output:
-1
3
I have to use 2 functions from a DLL in CTypes. Those functions have a void* as argument. But whatever I try, I can't make it work. I get an error telling me that I use the wrong type. I have looked on many posts and read the doc, but I can't figure it out.
Any help would be appreciated. I'm using Python 2.7 on windows.
My C functions are:
void WriteRam(unsigned address, unsigned length, void* buffer)
void ReadRam(unsigned address, unsigned length, void* buffer)
In Python, I'm trying to pass a list to the functions, like this:
audioVolume = 32767
for i in range(buffSize):
txBuff.append(int(audioVolume * math.sin(i)) )
WriteRam(0, 64, txBuff)
My Python functions are:
WriteRam = DPxDll['DPxWriteRam']
def DPxWriteRam(address=None, length=None, buffer=None):
#test = ctypes.c_void_p.from_buffer(buffer) # not working
#p_buffer = ctypes.cast(buffer, ctypes.c_void_p) # not working
p_buffer = ctypes.cast(ctypes.py_object(buffer), ctypes.c_void_p) # not working
#p_buffer = ctypes.c_void_p() # not working
WriteRam.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p]
WriteRam(address, length, ctypes.byref(p_buffer))
Assuming txBuff is a list of integers, then you'll need to pack them into an array. The following code ought to work, but I can't test it...
def DPxWriteRam(address, int_list):
int_size = ctypes.sizeof(ctypes.c_int)
item_count = len(int_list)
total_size = int_size * item_count
packed_data = (ctypes.c_int * item_count)(*int_list)
WriteRam(ctypes.c_uint(address), ctypes.c_uint(total_size), packed_data)
DPxWriteRam(whatever, [0, 1, 2, 3])
...although if WriteRam is pretty much just doing a memcpy(), then you could just use this...
import ctypes
libc = ctypes.CDLL('msvcrt.dll')
def DPxWriteRam(address, int_list):
int_size = ctypes.sizeof(ctypes.c_int)
item_count = len(int_list)
total_size = int_size * item_count
packed_data = (ctypes.c_int * item_count)(*int_list)
libc.memcpy(address, packed_data, total_size)
...which I can test...
>>> l = range(4)
>>> p = libc.malloc(1000)
>>> DPxWriteRam(p, l)
>>> s = ' ' * 16
>>> libc.memcpy(s, p, 16)
>>> print repr(s)
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'
I want to get the handle of every new Dialog which pops up from a specific application.
I understand I should set a hook with SetWinEventHook which is in user32.dll in windows, but I don't know how to do that in python. Would you give me an example ?
Here's a very simple example that prints to the console the window text for each dialog that is opened:
import sys
import time
import ctypes
import ctypes.wintypes
EVENT_SYSTEM_DIALOGSTART = 0x0010
WINEVENT_OUTOFCONTEXT = 0x0000
user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32
ole32.CoInitialize(0)
WinEventProcType = ctypes.WINFUNCTYPE(
None,
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD
)
def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime):
length = user32.GetWindowTextLengthA(hwnd)
buff = ctypes.create_string_buffer(length + 1)
user32.GetWindowTextA(hwnd, buff, length + 1)
print buff.value
WinEventProc = WinEventProcType(callback)
user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
hook = user32.SetWinEventHook(
EVENT_SYSTEM_DIALOGSTART,
EVENT_SYSTEM_DIALOGSTART,
0,
WinEventProc,
0,
0,
WINEVENT_OUTOFCONTEXT
)
if hook == 0:
print 'SetWinEventHook failed'
sys.exit(1)
msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
user32.TranslateMessageW(msg)
user32.DispatchMessageW(msg)
user32.UnhookWinEvent(hook)
ole32.CoUninitialize()