cx_Freeze exe file opens and then closes - python

My code converter code is down here:
import os
os.environ['TCL_LIBRARY'] = "C:\\Program Files (x86)\\Python35-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files (x86)\\Python35-32\\tcl\\tk8.6"
from cx_Freeze import setup, Executable
if __name__.endswith('__main__'):
setup(name = "Dodge The Blocks",
version = "2.0",
description = 'A fun little game for when your bored',
executables = [Executable(r"C:\Users\Harshal\Desktop\GameWIP.py")]
)
I also wanted to ask that what does this mean:
if __name__.endswith('__main__'):

Regarding the first part of your question: see this answer for a working setup script to freeze an application relying on tkinter using cx_Freeze 5.1.1 (and also see my comment to your question)
Regarding the second part of your question
what does this mean:
if __name__.endswith('__main__'):
See What does if __name__ == "__main__": do?
You probably got the modified version you are using from this issue or a similar one. In any case, this line and its modification might be relevant for the main application, but is not necessary in the setup script and should be removed from there.

Related

GUI application runs in Spyder and cmd but not as a standalone .exe [duplicate]

I've been dealing with this for days now and hope to find some help. I developed a GUI-application with imported modules tkinter, numpy, scipy, matplotlib, which runs fine in python itself. After having converted to an exe everything works as expected, but NOT the matplotlib section. When I press my defined plot button, the exe simply closes and doesn't show any plots.
So I thought to make a minimal example, where I simply plot a sin-function and I'm facing the same issue:
Works perfect in python, when converting it to an exe it crashes when pressing the plot button. Here is the minimal example:
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
class MainWindow(tk.Frame):
def __init__(self):
tk.Frame.__init__(self,bg='#9C9C9C',relief="flat", bd=10)
self.place(width=x,height=y)
self.create_widgets()
def function(self):
datax = np.arange(-50,50,0.1)
datay = np.sin(datax)
plt.plot(datax,datay)
plt.show()
def create_widgets(self):
plot = tk.Button(self, text='PLOT', command=self.function)
plot.pack()
x,y=120,300
root=tk.Tk()
root.geometry(str(x)+"x"+str(y))
app = MainWindow()
app.mainloop()
And here is my corresponding setup.py for converting with cx_Freeze:
import cx_Freeze
import matplotlib
import sys
import numpy
import tkinter
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [cx_Freeze.Executable("test.py", base=base)]
build_exe_options = {"includes": ["matplotlib.backends.backend_tkagg","matplotlib.pyplot",
"tkinter.filedialog","numpy"],
"include_files":[(matplotlib.get_data_path(), "mpl-data")],
"excludes":[],
}
cx_Freeze.setup(
name = "test it",
options = {"build_exe": build_exe_options},
version = "1.0",
description = "I test it",
executables = executables)
Any ideas that might solve the issue are highly appreciated. I'm working on a 64-bit Windows10 machine and I'm using the WinPython Distribution with Python 3.4.3.
I found a potential solution (or at least an explanation) for this problem while testing PyInstaller with the same test.py. I received error message about a dll file being missing, that file being mkl_intel_thread.dll.
I searched for that file and it was found inside numpy folder.
I copied files matching mkl_*.dll and also libiomp5md.dll to the same directory where the test.exe created by python setup.py build was. After this the minimal test.exe showed the matplotlib window when pressing the plot button.
The files were located in folder lib\site-packages\numpy\core.
I really wanted to post this as a comment, but I don't have the reputation. This is mostly a followup to J.J. Hakala's answer about how to find the cause.
If one changes the base to "Console", i.e. using
base = "Console"
rather than
base = "Win32GUI"
a console will also pop up when the program starts and this error is printed
Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll.
Which can help finding the cause of the problem pretty faster.
I thought this would be worth mentioning, since this trick can also be helpful to diagnose other problems. In the final release, one can revert back to Win32GUI to avoid the extra console. I should give the credits to this other stackoverflow post
I have followed #J.J. Hakala's answer, but I found that it's not necessary copy all mkl_*.dll and libiomp5md.dll files. For me it worked with libiomp5md.dll mkl_core.dll mkl_def.dll mkl_intel_thread.dll. This helps to reduce the final bundle size in ~500MB.
Also, you can include the files you want to copy in the include_files option. You also could only want to include them if sys.platform is win32.
I'm using Anaconda as well as #Matt Williams, so, changing a bit the OP's code:
import cx_Freeze
import matplotlib
import sys
import numpy
import tkinter
import os
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
build_exe_options = {"includes": ["matplotlib.backends.backend_tkagg","matplotlib.pyplot",
"tkinter.filedialog","numpy"],
"include_files":[(matplotlib.get_data_path(), "mpl-data")],
"excludes":[],
}
base = None
if sys.platform == "win32":
base = "Win32GUI"
DLLS_FOLDER = os.path.join(PYTHON_INSTALL_DIR, 'Library', 'bin')
dependencies = ['libiomp5md.dll', 'mkl_core.dll', 'mkl_def.dll', 'mkl_intel_thread.dll']
for dependency in dependencies:
build_exe_options['include_files'].append(os.path.join(DLLS_FOLDER, dependency))
executables = [cx_Freeze.Executable("test.py", base=base)]
cx_Freeze.setup(
name = "test it",
options = {"build_exe": build_exe_options},
version = "1.0",
description = "I test it",
executables = executables)
Check if you have numpy+mkl package installed. Uninstalling numpy and installing numpy+mkl package solved my issue of getting error related to mkl_intel_thread.dll

cx_Freeze : DLL load error with tkinter

I am currently trying to use cx_Freeze to create a .exe file for my python scripts.
First, do cx_freeze get all data on the folder into the build folder?
Secondly, I'm having an issue when launching the .exe file. The fact that the first file opens the second one could be the issue ?
The console opened and closed, according to another post on Stackoverflow, I created a .bat file containing :
myfilename.exe%1
pause
to check out what the issue is and I got this issue :
Issue
I've really no idea what to do next since I tried many things on the setup.py to make things working.
Here is the setup.py :
"""setup.py"""
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = "C:\\Users\\Roukira\\AppData\\Local\\Programs\\Python\\Python36\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Users\\Roukira\\AppData\\Local\\Programs\\Python\\Python36\\tcl\\tk8.6"
build_exe_options = {"includes": ["tkinter"]}
setup(name="todolist",
version="0.1",
description = "A simple to do list with differnt tabs per account.",
options = {"build_exe": build_exe_options},
executables = [Executable("login_system.py",base=None)])
I'm only using pillow as an external module but it doesn't seem to be the issue.
Thanks for your help by advance !
EDIT : I managed to fix it by adding the ddl missing files path inside the "include_files" option:
build_exe_options = {"packages": ["os", "tkinter"], "include_files": ["to_do_list.py","336sur525.gif","384sur540.gif",
"accounts.txt","button_hide_2.gif","button_quit_2.gif","choose.gif","icone.ico","user.gif",
r"C:\Users\Roukira\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll",
r"C:\Users\Roukira\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll"]}
My script was using a subprocess.call function to call another script, so it didn't work after becoming .exe, I added the .py file inside the "include_files" and it worked as intended.

cx_Freeze converted GUI-app (tkinter) crashes after pressing plot button

I've been dealing with this for days now and hope to find some help. I developed a GUI-application with imported modules tkinter, numpy, scipy, matplotlib, which runs fine in python itself. After having converted to an exe everything works as expected, but NOT the matplotlib section. When I press my defined plot button, the exe simply closes and doesn't show any plots.
So I thought to make a minimal example, where I simply plot a sin-function and I'm facing the same issue:
Works perfect in python, when converting it to an exe it crashes when pressing the plot button. Here is the minimal example:
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
class MainWindow(tk.Frame):
def __init__(self):
tk.Frame.__init__(self,bg='#9C9C9C',relief="flat", bd=10)
self.place(width=x,height=y)
self.create_widgets()
def function(self):
datax = np.arange(-50,50,0.1)
datay = np.sin(datax)
plt.plot(datax,datay)
plt.show()
def create_widgets(self):
plot = tk.Button(self, text='PLOT', command=self.function)
plot.pack()
x,y=120,300
root=tk.Tk()
root.geometry(str(x)+"x"+str(y))
app = MainWindow()
app.mainloop()
And here is my corresponding setup.py for converting with cx_Freeze:
import cx_Freeze
import matplotlib
import sys
import numpy
import tkinter
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [cx_Freeze.Executable("test.py", base=base)]
build_exe_options = {"includes": ["matplotlib.backends.backend_tkagg","matplotlib.pyplot",
"tkinter.filedialog","numpy"],
"include_files":[(matplotlib.get_data_path(), "mpl-data")],
"excludes":[],
}
cx_Freeze.setup(
name = "test it",
options = {"build_exe": build_exe_options},
version = "1.0",
description = "I test it",
executables = executables)
Any ideas that might solve the issue are highly appreciated. I'm working on a 64-bit Windows10 machine and I'm using the WinPython Distribution with Python 3.4.3.
I found a potential solution (or at least an explanation) for this problem while testing PyInstaller with the same test.py. I received error message about a dll file being missing, that file being mkl_intel_thread.dll.
I searched for that file and it was found inside numpy folder.
I copied files matching mkl_*.dll and also libiomp5md.dll to the same directory where the test.exe created by python setup.py build was. After this the minimal test.exe showed the matplotlib window when pressing the plot button.
The files were located in folder lib\site-packages\numpy\core.
I really wanted to post this as a comment, but I don't have the reputation. This is mostly a followup to J.J. Hakala's answer about how to find the cause.
If one changes the base to "Console", i.e. using
base = "Console"
rather than
base = "Win32GUI"
a console will also pop up when the program starts and this error is printed
Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll.
Which can help finding the cause of the problem pretty faster.
I thought this would be worth mentioning, since this trick can also be helpful to diagnose other problems. In the final release, one can revert back to Win32GUI to avoid the extra console. I should give the credits to this other stackoverflow post
I have followed #J.J. Hakala's answer, but I found that it's not necessary copy all mkl_*.dll and libiomp5md.dll files. For me it worked with libiomp5md.dll mkl_core.dll mkl_def.dll mkl_intel_thread.dll. This helps to reduce the final bundle size in ~500MB.
Also, you can include the files you want to copy in the include_files option. You also could only want to include them if sys.platform is win32.
I'm using Anaconda as well as #Matt Williams, so, changing a bit the OP's code:
import cx_Freeze
import matplotlib
import sys
import numpy
import tkinter
import os
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
build_exe_options = {"includes": ["matplotlib.backends.backend_tkagg","matplotlib.pyplot",
"tkinter.filedialog","numpy"],
"include_files":[(matplotlib.get_data_path(), "mpl-data")],
"excludes":[],
}
base = None
if sys.platform == "win32":
base = "Win32GUI"
DLLS_FOLDER = os.path.join(PYTHON_INSTALL_DIR, 'Library', 'bin')
dependencies = ['libiomp5md.dll', 'mkl_core.dll', 'mkl_def.dll', 'mkl_intel_thread.dll']
for dependency in dependencies:
build_exe_options['include_files'].append(os.path.join(DLLS_FOLDER, dependency))
executables = [cx_Freeze.Executable("test.py", base=base)]
cx_Freeze.setup(
name = "test it",
options = {"build_exe": build_exe_options},
version = "1.0",
description = "I test it",
executables = executables)
Check if you have numpy+mkl package installed. Uninstalling numpy and installing numpy+mkl package solved my issue of getting error related to mkl_intel_thread.dll

Py2exe compiles properly but the built application doesn't work

I am using Python 2.7 to build my application. Within it, I used few packages which are numpy, scipy, csv, sys, xlwt, time, wxpython and operator.
All the above packages are in 64-bit, and I am using python 2.7(64-bit version) in Aptana Studio 3(64-bit version) in Windows 7 Professional (64-bit version).
At last, I'd like to compile my project to an application using following code, the file name is py2exeTest.py:
from distutils.core import setup
import numpy # numpy is imported to deal with missing .dll file
import py2exe
setup(console=["Graphical_Interface.py"])
Then in cmd, I switched to the directory of the project and used following line to compile it:
python py2exeTest.py py2exe
Everything goes well, it generates an application under dist directory, and the application name is Graphical_Interface.exe.
I double clicked it, but there is a cmd window appears, and a python output windows flashes, then both of them disappeared. I tried to run the application as an administrator, the same outcome I've had.
May I know how to work this out?
Thanks!
EDIT:
I've managed to catch the error information that flashes on the screen. The error info I had is:
Traceback (most recent call last):
File "Graphical_Interface.py", line 397, in <module>
File "Graphical_Interface.py", line 136, in __init__
File "wx\_core.pyc", line 3369, in ConvertToBitmap
wx._core.PyAssertionError: C++ assertion "image.Ok()" failed at ..\..\src\msw\bitmap.cpp(802) in wxBitmap::CreateFromImage(): invalid image
I used one PNG image in the project, the code is like follows:
self.workflow = wx.Image("Work Flow.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.StaticBitmap(self.panel_settings, -1, self.workflow, (330,270), (self.workflow.GetWidth(), self.workflow.GetHeight()))
I tried to comment the above chunk out from the project, and the application works properly. However, I need the image to show up in the application.
May I know how to deal with it?
Thanks.
Hiding console window of Python GUI app with py2exe
When compiling graphical applications you can not create them as a console application because reasons (honestly can't explain the specifics out of my head), but try this:
from distutils.core import setup
import numpy
import py2exe
import wxpython
setup(window=['Graphical_Interface.py'],
options={"py2exe" { 'boundle_files' : 1}})
Also consider changing to:
http://cx-freeze.sourceforge.net/
It works with Python3 and supports multiple platforms.
A cx_freeze script would look something like:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
includefiles = ['/folder/image.png']
setup( name = "GUIprog",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options, 'include_files' : includefiles},
executables = [Executable("Graphical_Interface.py", base=base)])
No worries, I've got the solution.
It turns out that the image is in the project folder rather than in the dist folder. So I have two solutions:
Copy the image into dist folder
Include the full path of the image in the code.
Thanks for your help.

running a python script as administrator

i'm writing an installer using py2exe which needs to run in admin to have permission to perform various file operations. i've modified some sample code from the user_access_controls directory that comes with py2exe to create the setup file. creating/running the generated exe works fine when i run it on my own computer. however, when i try to run the exe on a computer that doesn't have python installed, i get an error saying that the import modules (shutil and os in this case) do not exist. it was my impression that py2exe automatically wraps all the file dependencies into the exe but i guess that this is not the case. py2exe does generate a zip file called library that contains all the python modules but apparently they are not used by the generated exe. basically my question is how do i get the imports to be included in the exe generated by py2exe. perhaps modification need to be made to my setup.py file - the code for this is as follows:
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
)
Try to set options={'py2exe': {'bundle_files': 1}}, and zipfile = None in setup section. Python will make single .exe file without dependencies. Example:
from distutils.core import setup
import py2exe
setup(
console=['watt.py'],
options={'py2exe': {'bundle_files': 1}},
zipfile = None
)
I rewrite your setup script for you. This will work
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
#the options is what you fail to include it will instruct py2exe to include these modules explicitly
options={"py2exe":
{"includes": ["sip","os","shutil"]}
}
)

Categories