Create exe file from Python file using cx_Freeze [duplicate] - python

This question already has answers here:
cx_Freeze: ImportError: No module named 'PyQt5.Qt'
(3 answers)
Closed 3 years ago.
Using cx_Freeze with PyQt5, I get the following error:
ImportError: No module named 'PyQt5.Qt'
My setup.py file is as follows:
from cx_Freeze import setup, Executable
base = None
executables = [Executable("Chemistry.py", base=base)]
packages = ["idna", "sys", "pandas", "PyQt5"]
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "<any name>",
options = options,
version = "<any number>",
description = '<any description>',
executables = executables
)
How do I fix this error? I am using Windows OS.

Try this solution to a similar question:
Remove "PyQt5" from the packages list
Let cx_Freeze copy the whole PyQt5 directory into the lib subdirectory of the build directory. You can do that by passing a (source, destination) tuple to the include_files list, which tells cx_Freeze to copy the source (a file or a whole directory) to a destination relative to the build directory (see the cx_Freeze documentation). Set the source to os.path.dirname(PyQt5.__file__), which gives the directory of the PyQt5 package (through its __init__.py file) of your Python installation, and the destination to "lib".
Furthermore, if your application really uses pandas, you also need to add "numpy" to the packages list, see cx_Freeze not able to build msi with pandas and Creating cx_Freeze exe with Numpy for Python
Altogether, try modify your setup.py script as follows:
import os
import PyQt5
include_files = [(os.path.dirname(PyQt5.__file__), "lib")]
packages = ["idna", "sys", "numpy", "pandas"]
options = {
'build_exe': {
'include_files':include_files,
'packages':packages,
},
}

Related

How to convert a python project into an executable file with all additional scripts?

I know there have been a bunch of questions already asked regarding this but none of them really helped me. Let me explain the whole project scenario so that I provide a better clarity to my problem. The directory structure is somewhat like this shown below:
Project Directory Layout
I need to convert this whole GUI based project (The main file is using Tkinter module to create GUI) into main.exe which I can share with others while making sure that all the additional files work exactly the same way it is working now when I run this main.py via Command Prompt. When I use this command with pyinstaller -
"pyinstaller --onefile --noconsole main.py"
It creates main.exe which shows "Failed to execute script" on running. Please provide me a detailed explanation on what should I do to achieve what I have stated above. Thank you in advance.
pyinstaller uses a few dirty tricks to compress a bunch of files into one
I recommend using cx_Freeze instead along with inno setup installer maker
do pip install cx_Freeze to install that and go here for inno setup
then copy the following into a file named setup.py in the same folder as your project
from cx_Freeze import setup, Executable
setup(name = "YOUR APP NAME" ,
version = "1.0.0" ,
description = "DESCRIPTION" ,
executables = [Executable("PYTHON FILE", base = "Win32GUI")]
)
lastly run python setup.py build
if you want as onefile download this file here
just edit the file a bit and use inno compiler to make into installer
Suppose our project has the following structure.
MyApp
|-models
| |-login.kv
|-data
| |-words.json
| |-audio.tar.gz
|-fonts
| |-FredokaOne.ttf
|-images
| |-gb.pngsound.png
| |-icon.ico
|-main.py
|-main.kv
|-draw.py
|-image.py
and depends on the following packages:
- kivy
- kivymd
- ffpyplayer
- gtts
First things first is to install cx_Freeze.
pip install cx_Freeze
Copy the following into a file named setup.py in the same folder as your project.
# https://cx-freeze.readthedocs.io/en/latest/distutils.html
import sys
from cx_Freeze import setup, Executable
includes = []
# Include your files and folders
includefiles = ['models/','data/','fonts/','images/','main.kv','draw.py','image.py']
# Exclude unnecessary packages
excludes = ['cx_Freeze','pydoc_data','setuptools','distutils','tkinter']
# Dependencies are automatically detected, but some modules need help.
packages = ['kivy','kivymd', 'ffpyplayer','gtts']
base = None
shortcutName = None
shortcutDir = None
if sys.platform == "win32":
base = "Win32GUI"
shortcutName='My App'
shortcutDir="DesktopFolder"
setup(
name = 'MyApp',
version = '0.1',
description = 'Sample python app',
author = 'your name',
author_email = '',
options = {'build_exe': {
'includes': includes,
'excludes': excludes,
'packages': packages,
'include_files': includefiles}
},
executables = [Executable('main.py',
base = base, # "Console", base, # None
icon='images/icon.ico',
shortcutName = shortcutName,
shortcutDir = shortcutDir)]
)
Lastly run.
python setup.py build
This command will create a subdirectory called build with a further subdirectory starting with the letters exe. and ending with the typical identifier for the platform that distutils uses. This allows for multiple platforms to be built without conflicts.
On Windows, you can build a simple installer containing all the files cx_Freeze includes for your application, by running the setup script as:
python setup.py bdist_msi
Cx_freeze references
Doc
Git Hub

cx_Freeze not able to build msi with pandas

Hi I have following cx_Freeze setup.py file for an application that uses
pandas module. When I generate msi I am facing issues. I looked all over the google for this but none of them are working for me.
include-files = ['aardvark.dll']
includes = []
excludes = []
base = "Win32GUI"
exe = Executable(
script="test.py",
initScript=None,
base=base,
targetName="test.exe",
copyDependentFiles=True,
compress=False,
appendScriptToExe=False,
appendScriptToLibrary=False,
shortcutDir="MyProgramMenu",
shortcutName=APP_NAME)
bdist_msi_options = {
"upgrade_code": UPGRADE_CODE,
"add_to_path" : False}
setup(
name=APP_NAME,
version=VERSION,
author="sri",
description='test Tool',
options={"build_exe": {"excludes":excludes,
"includes":includes,
"include_files":includefiles},
"bdist_msi" : bdist_msi_option},
executables=[exe])
When I build msi with cx_Freeze==4.3.4 it gives
this error:
cx_Freeze.freezer.ConfigError: no file named sys (for module collections.sys)
and when I use cx_Freeze >= 5.0.0 the msi is created but after installing this gives
ImportError: Missing required dependencies['numpy']
I tried all the available stack overflow work around but none of them is working any suggestion will be a great help thanks in advance.
pandas depends on numpy and you need to explicitly add numpy to the packages list of the build_exe options in order that cx_Freezeincludes numpycorrectly, see Creating cx_Freeze exe with Numpy for Python
Try to add the following to your setup script
packages = ['numpy']
and to modify the options according to
options={"build_exe": {"excludes":excludes,
"includes":includes,
"include_files":includefiles,
"packages":packages},
"bdist_msi" : bdist_msi_option},

Cannot load mkl_intel_thread.dll on python executable

I'm trying to create an executable python program that runs on windows without python being installed, for this I'm using cx_Freeze. But I get the following error: "Cannot load mkl_intel_thread.dll"
On my PC, which has python installed (miniconda3), I built the executable using cx_Freeze, and when I ran the executable I also would get "Cannot load mkl_intel_thread.dll". I fixed this by going to my python folder, Library\bin, and copied the mkl_intel_thread.dll file to where the executable is placed. The problem is, when moving the whole folder to another PC (without python installed), this error reappears, even though the mkl_intel_thread.dll is in the folder.
File that I want to distribute (plot.py):
import matplotlib.pyplot as plt
a = [0, 1, 2]
b = [0, 2, 0]
plt.fill(a, b, 'b')
plt.show()
cx_Freeze setup file (setup.py):
import cx_Freeze
import sys
import matplotlib
import numpy
import os
os.environ['TCL_LIBRARY'] = "C:\\Miniconda3\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Miniconda3\\tcl\\tk8.6"
executables = [cx_Freeze.Executable("plot.py")]
build_exe_options = {"includes":['numpy.core._methods',
'numpy.lib.format', 'matplotlib.backends.backend_tkagg']}
cx_Freeze.setup(
name = "script",
options = {"build_exe": build_exe_options},
version = "0.0",
description = "A basic example",
executables = executables)
EDIT:
Try to copy all files starting with mkl you find under Library\bin or numpy\core into the build folder, as well as libiomp5md.dll, see Python Pyinstaller 3.1 Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll and cx_freeze converted GUI-app (tkinter) crashes after pressing plot-Button.
Once you have found out which file(s) need(s) to be manually copied, you can let cx_Freeze include the necessary file(s) by using the include_files list of the build_exe options (see code snippet below). If necessary, you can use a tuple (source, destination) as item in the include_files list to let cx_Freeze copy a file from source to a specific destination into the build directory, see the cx_Freezedocumentation.
I see further potential problems in the setup script you've posted in your question:
include the whole numpy packages using the packages list of the build_exe options, it is easier and maybe safer
it is safer to dynamically find out the location of the TCL/TK DLLs
for cx_Freeze 5.1.1, the TCL/TK DLLs need to be included in a lib subdirectory of the build directory
In summary, try t o use
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
build_exe_options = {'packages': ['numpy'],
'includes': ['matplotlib.backends.backend_tkagg'],
'include_files': [(os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
os.path.join('lib', 'tcl86t.dll')),
(os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
os.path.join('lib', 'tk86t.dll'))
# add here further files which need to be included as described in 1.
]}
in your setup script.
A similar issue affects cx_Freeze 6.1 or 6.2: the executable does not launch, either without error message or with
INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll.
Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll.
Configuration:
Windows 10
Python 3.8.5 installed from https://www.python.org/
numpy 1.19.1+mkl installed with pip using wheel from https://www.lfd.uci.edu/~gohlke/pythonlibs/
various python modules installed using pip
This is also observed with Python 3.6.8 or earlier versions of numpy such as e.g. 1.18.4+mkl or 1.19.0+mkl.
I've observed that cx_Freeze includes 3 DLLs mkl_rt.dll, python38.dll, and vcruntime140.dll in the subdirectory lib\numpy\core of the build directory, whereas the original installation does not contain any DLL in the subdirectory site-packages\numpy\core (all DLLs are in site-packages\numpy\DLLs). If I manually remove mkl_rt.dll from the subdirectory lib\numpy\core of the build directory after building the application with cx_Freeze, the issue disappears and the application works.
This solution can be implemented by adding the following code at the end of the setup.py script:
numpy_core_dir = os.path.join(dist_dir, 'lib', 'numpy', 'core')
for file_name in os.listdir(numpy_core_dir):
if file_name.lower().endswith('.dll'):
file_path = os.path.join(numpy_core_dir, file_name)
os.remove(file_path)
where dist_dir is the build directory generated by cx_Freeze (passed to the build_exe option).
Just copy these four files in cx_freeze generated build folder
mkl_core.dll
mkl_def.dll
mkl_intel_thread.dll
mkl_mc3.dll
Manage to find a solution to this by downgrading numpy==1.18.2 from numpy==1.19.1 when using cx_Freeze==6.5.3.

cx_freeze executable - Py_Initialize: Unable to load the file system codec

I'm using cx_freeze to pack my Python script as a standalone executable.
The exe is running fine on the machine it was packed (with python 3.5 and all the relevant packages).
But when I copied the folder cx_freeze created to another machine the I got this error:
My cx_freeze script:
import sys
import numpy
import os.path
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name = "DocSum",
version = "1.0",
options = {"build_exe": {"packages":["idna","asyncio", "encodings","numpy", "jinja2.ext"]}},
description = "DocSumRESTfulServer",
executables = [Executable("DocSumRESTfulServer.py", base = None)]
)
Any idea what could be the reason? I thought that the exe should be a standalone (run on machines without python). Am I wrong?
It seems that not all dependencies were compiled successfully.
If you want to have a standalone executable, I recommend pyinstaller.
Just pip install it then:
pyinstaller.exe --onefile yourFile.py
The --onefile flag is used to package everything into a single executable. Your executable file would be found on the dist folder.
You could also try this site.
I had the same problem. At the end I discovered that I need to copy also my python37.dll and the lib directory.
If the exe, dll and the directory are on the same directory, it works.
I would like to have a single exe too.

Is it possible to use cx_freeze on a python 3 project using the pip module?

I am writing an installation program for a larger program I am writing, and I am using CxFreeze to convert it to an executable file, however, when I run the .exe file, it crashes with the line "import pip", and brings up (as shown below), so basically my question is: Is it possible to use CxFreeze on an application with pip imported?
Edit:
Here are all the files I am using:
setup.py (V1):
from cx_Freeze import *
import os, pip
setup(name=("ARTIST"),
version = "1",
description = "ARTIST installation file",
executables = [Executable("Install ARTIST.py"), Executable("C:\\Python34\\Lib\\site-packages\pip\\__init__.py")],
)
This brings up the error:
setup.py (V2):
from cx_Freeze import *
import os, pip
setup(name=("ARTIST"),
version = "1",
description = "ARTIST installation file",
executables = [Executable("Install ARTIST.py"],
options = {"build_exe": {"packages":[pip]}}
)
This brings up an error in the setup.bat file:
Edit:
If anyone wants to look at the website where I am publishing the larger program, here is the link:
alaricwhitehead.wix.com/artist
Edit2:
this is the error i get when i use py2exe:
Edit3:
here is a copy of the code:
https://www.dropbox.com/s/uu46iynm8fr8agu/Install%20ARTIST.txt?raw=1
please note: I didn't want to have to post a link to it, but it was too long to post directly.
The are two problems in your setup script. The first problem is that you specified extra modules to include in your frozen application under the packages option of the build_exe command: packages is for specifying which packages of your application you need to include, for the external modules (such as pip) you need to use includes. The second problem is that you need to pass to includes a list of strings of modules and not the module itself:
setup(
name=("ARTIST"),
version="1",
description="ARTIST installation file",
options={
'build_exe': {
'excludes': [], # list of modules to exclude
'includes': ['pip'], # list of extra modules to include (from your virtualenv of system path),
'packages': [], # list of packages to include in the froze executable (from your application)
},
},
executables=[
Executable(
script='run.py', # path to the entry point of your application (i.e: run.py)
targetName='ARTIST.exe', # name of the executable
)
]
)

Categories

Resources