cx_Freeze converted exe: window closes immediately - python-3.x

I am trying to just convert my pygame python py to a .exe file using cx_Freeze. The setup file executes correctly and without error, but the issue is that when I run my .exe file the console window (the black cmd-like window)will open quickly and close. My .py which I want to convert is called Salary.py, and it includes a .input('str') codes in it so that the
user can decide which csv file they want to use.
Description of my Salary.py: if the user input an interger, Salary.py help them to parse through one existed csv file and run the
script and output to another csv file.
Chinese is included inside the code.
Once again, there is no error running when I run Salary.py in python3.6, and no error when building the exe file for now.
The setup.py I am using:
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = r'D:\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'D:\Anaconda3\tcl\tcl8.6'
setup(name='Salary',
version='0.1',
description='Salarycount',
executables= [Executable("Salary.py")])
I try to execute the Salary.exe in cmd. And it gave this to me:
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
module.run()
File "D:\Anaconda3\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run
exec(code, m.__dict__)
File "Salary.py", line 8, in <module>
File "D:\Anaconda3\lib\site-packages\pandas\__init__.py", line 19, in <module>
"Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']
Apperently, numpy has already installed to my python packages, I don't even know what does it mean.
my environment:
Anaconda 3
python 3.6
cx-Freeze 6.0b1

It looks like your Salary.py script uses the pandas package, is this correct? The pandas package requires the numpy package to work, and one needs to tell cx_Freeze explicitly to include the numpy package. Try to add the following options to setup:
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = r'D:\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'D:\Anaconda3\tcl\tcl8.6'
setup(name='Salary',
version='0.1',
description='Salarycount',
options={'build_exe': {'packages': ['numpy']}},
executables= [Executable("Salary.py")])

Related

TypeError after converting python game to executable [duplicate]

I am trying to build a python script via PyInstaller. I have used the following commands to configure, generate a spec file, and build:
wget pyinstaller.zip, extracted it, python Configure.py, etc, then:
python pyinstaller/Makespec.py --onefile myscript.py
python pyinstaller/Build.py myscript.spec
Here is the spec file it generated:
# -*- mode: python -*-
a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'icinga.py'],
pathex=['/home/user/projects/icinga_python/releases/v2.1'])
pyz = PYZ(a.pure)
exe = EXE( pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name=os.path.join('dist', 'myscript'),
debug=False,
strip=False,
upx=True,
console=1 )
This built an executable file in dist/ directory. When trying to run this file, I get the following:
Traceback (most recent call last):
File "<string>", line 12, in <module>
File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
raise ImportError, "No module named %s" % fqname
ImportError: No module named mysql
If I moved this executable into the directory of the actual Python code, it gave different results:
Traceback (most recent call last):
File "<string>", line 12, in <module>
File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 436, in importHook
mod = _self_doimport(nm, ctx, fqname)
File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 521, in doimport
exec co in mod.__dict__
File "CLUSTER/mysql/icingasql.py", line 13, in <module>
import urllib2
File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
raise ImportError, "No module named %s" % fqname
ImportError: No module named urllib2
In the ... pyinstaller docs I see that --onefile is the option I need/want, but for some reason not everything is being compiled in.
The script is not really including anything fancy, just little quick modules I wrote for sql statements, and parsing certain websites.
The problem is that pyinstaller won't see second level imports. So if you import module A, pyinstaller sees this. But any additional module that is imported in A will not be seen.
There is no need to change anything in your python scripts. You can directly add the missing imports to the spec file.
Just add the following in a = Analysis(...):
hiddenimports=["mysql"],
This should be the result:
a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'icinga.py'],
pathex=['/home/user/projects/icinga_python/releases/v2.1'], hiddenimports=["mysql"],)
After that run pyinstaller with the spec file as an argument.
This error can ocurre when you have dynamic imports in your code. In that case, pyinstaller don't include those packages in exe file. In that case you can:
Add unused import of those packages in your code
Tell pyinstaller to include it
One file option does not change anything in running your code. If you create --onefile exe all files created by pyinstaller are packed to exe file, and unpacked to local temp every time you run exe.
just gonna add my 2 cents because I encountered the same problem today - 6 years later :D
For Windows:
1) cmd => rightclick => with admin rights
2) Enter in cmd: "pip install pyinstaller"
3) navigate in cmd to the folder of "yourMain.py"
4) Enter in cmd: "pyinstaller --onefile --windowed yourMain.py"
5) If you import other scripts / data in "yourMain.py":
Manually enter the folder "dist" (gets created - where "yourMain.exe" should be by now),
and copy your scripts or folder structure there
(e.g. /assets/sounds; /assets/graphics; /scripts; anotherscript.py )
Then I was able to run the exe by double clicking.
Turned out to be pretty easy. What did the trick for me was the "--onefile" and adding my other files to the "dist" folder.
The "--windowed" is just so the python command window won't pop up when you start the exe.

cx_Freeze ConfigError: No file named C:\Python\Scripts\cxfreeze.exe\__main__.py (for module __main__)

I would like to create a .exe file of a file named ZCasinoinsulte.py located in C:\Python\Scripts. Moreoever, every time I execute cxfreeze ZCasinoinsulte.py it never works and tells me it does not find _main_.py in cxfreeze.exe.
Specs: I have python 3.9.1 on Windows 10 64bit.
I have installed cx_Freeze-6.5.1 with whl.
It does create an exe file, but it opens and shuts down instantly (even though I put os.system("pause") in ZCasinoinsulte.py).
old code
Any help would be appreciated :D
Edit: I have used the cxfreeze version 6.4.2 and the code runs better without errors. But the exe file closes as soon as I clic on it.
Here is my pip list traceback:
C:\Users\Hmili>pip list
Package Version
------------------ -------
cx-Freeze 6.4.2
importlib-metadata 3.4.0
pip 20.3.3
setuptools 49.2.1
zipp 3.4.0
Here is the traceback when I execute the exe file from cmd:
C:\Python\Mes fichiers python\dist>ZCasinoinsulte.exe
Traceback (most recent call last):
File "c:\python\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 41, in run
module.run()
File "c:\python\lib\site-packages\cx_Freeze\initscripts\Console.py", line 36, in run
exec(code, m.__dict__)
File "ZCasinoinsulte.py", line 3, in <module>
File "c:\python\lib\site-packages\cx_Freeze\__init__.py", line 1, in <module>
import setuptools
File "c:\python\lib\site-packages\setuptools\__init__.py", line 24, in <module>
from setuptools.depends import Require
File "c:\python\lib\site-packages\setuptools\depends.py", line 6, in <module>
from .py33compat import Bytecode
File "c:\python\lib\site-packages\setuptools\py33compat.py", line 11, in <module>
from setuptools.extern.six.moves import html_parser
File "c:\python\lib\site-packages\setuptools\_vendor\six.py", line 92, in __get__
result = self._resolve()
File "c:\python\lib\site-packages\setuptools\_vendor\six.py", line 115, in _resolve
return _import_module(self.mod)
File "c:\python\lib\site-packages\setuptools\_vendor\six.py", line 82, in _import_module
__import__(name)
ModuleNotFoundError: No module named 'html.parser'
Here are the first ten lines of ZCasinoinsulte.py:
# -*-coding:Latin-1 -*
import os,time
from cx_Freeze import setup, Executable
from random import randrange
argent=3000
while argent>0:
condition1=0
condition2=0
argent=int(argent)
How do I resolve this? (Thanks for the help by the way :) )
I reverted cx_Freeze back to version 6.4.2, seemed to compile fine after that
pip install --upgrade cx-Freeze==6.4.2
Seems to be a bug or something.
First I downgraded pip as James Mackey advised me. The code ran properly and created an exe file. So the first issue was a comptability one.
Moreover, the exe file created crashed instantly when executed. From the traceback of the execution of ZCasinoinsulte.exe with cmd, James Mackey figured the third line of ZCasinoinsulte.py had an error related to it.
The third line of ZCasinoinsulte.py was:
from cx_Freeze import setup, Executable
I erased this line as it has nothing to do with the actual code.
I opened cmd and executed again the command: cxfreeze ZCasinoinsulte.py. The exe file now functions properly.

cx_freeze No module named os

I wanna freeze my python scripts into .exe files. I used to use pyinstaller but now the antivirus says it's a virus (so please don't tell me to use pyinstaller - unless you know how to fix the antivirus problem). I'm trying to use cx_freeze. I had problems with modules that didn't work so I entered them in the setup.py file. So here is my setup.py code:
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["matplotlib", "os", "pandas", "math", "sklearn","yellowbrick", "PySimpleGUI"]}
setup(name="Clustering Tool",
version="1.5",
description="",
options = {"build_exe": build_exe_options},
executables = [Executable("clustering_tool_1.5.py")])
problem when the exe is created it launches and the console blinks and dies. I run the script through command prompt and it says :
Traceback (most recent call last):
File "<frozen zipimport>", line 259, in load_module
File "C:\Program Files (x86)\Python38-32\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 7, in <module>
import os
ModuleNotFoundError: No module named 'os'
but I entered the os module with my packages. Am I missing something here? How can I include the os module in here?
I guess single file build is unsupported one please check FAQ of cx-freeze here
and more over os is built-in you dont have to explicitly install.

Pip install openslide completes successfully but when I import it "the specified module is not found"

I need to open SVS images in Python 3.7 and it seems that Openslide is the only module capable of opening images of that size (30k*30k pixels). I have used pip install openslide-python as well as python -m pip install openslide-python and pip 3 install... etc.
I know the module has been successfully installed because if I run any of those commands again the command line returns requirement already satisfied however when I run Python and try to import openslide it gives the error at the bottom.
My guess was that the .whl or .tar.gz files were in the wrong path so I made a bunch of copies and put them in the openslide folders within the Anaconda3 folder. The error persists. I have included the full error code below for clarity.
Extra: If I run help("modules") openslide shows up along with numpy, math, sklearn etc. I can import and run all other modules without issue.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\brimk\Anaconda3\lib\site-packages\openslide\__init__.py", line 29, in <module>
from openslide import lowlevel
File "C:\Users\brimk\Anaconda3\lib\site-packages\openslide\lowlevel.py", line 41, in <module>
_lib = cdll.LoadLibrary('libopenslide-0.dll')
File "C:\Users\brimk\Anaconda3\lib\ctypes\__init__.py", line 434, in LoadLibrary
return self._dlltype(name)
File "C:\Users\brimk\Anaconda3\lib\ctypes\__init__.py", line 356, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
My issue was resolved by the answer from my hero!
It seems that, at least for Openslide, running Python from the Path to the Bin is the easiest solution. It can be done this way.
Download the Windows Binary here.
Extract the download to whatever path you want.
Open command window
pip3 install openslide-python (pip2 if Python 2)
cd C:\Users\Path\to\Openslide-Win64-20171122\bin
python
import openslide
In the future you will have to run python from the path to the Openslide bin (Step 4). This can be done more rigorously by adding that file path to the PATH as described in detail here as well as in the answer above.

ImportError with cx_freeze and pywin32: Module 'pythoncom' isn't in frozen sys.path

I am attempting to create a .exe on Windows 7 from a python3 script using cx_freeze. the Script involves using pywin32 to manipulate Excel files. I can build the .exe successfully from my setup.py file; however, when I run the .exe, the following error is thrown:
Traceback (most recent call last):
File
"C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py",
line 27, in exec(code,m_dict_)
File "MyScript.py", line
12, in < module >
File
"C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1558, in
_find_and_load
File "C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1505, in
_find_and_load_unlocked
File "C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 313, in
_call_with_frames_removed
File "C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1558, in
_find_and_load
File "C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1525, in
_find_and_load_unlocked
File "C:\Python33\lib\site-packages\win32com__init__.py", line 6, in
< module>
import pythoncom
File
"C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1558, in
_find_and_load
File "C:\Python\64-bit\3.3\lib\importlib_bootstrap.py", line 1525, in
_find_and_load_unlocked
File "C:\Python33\lib\site-packages\pythoncom.py", line 3, in
pywintypes._import_pywin32_system_module_("pythoncom", globals())
File "C:\Python33\lib\site-packages\win32\lib\pywintypes.py", line 61,
in _import_pywin32_system_module_
raise ImportError("Module '%s'
isn't in frozen sys.path %s" % (modname, sys.path))
ImportError: Module 'pythoncom' isn't in frozen sys.path
['C:\Python33\build\exe.win-amd64\3.3\MyScript.exe',
'C:\Python33\build\exe.win-amd64\3.3',
'C:\Python33\build\exe.win-amd64\3.3\MyScript.zip',
'C:\Python33\build\exe.win-amd64\3.3\library.zip']
Here is what my setup.py file currently looks like:
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
includes = []
packages = []
executables = [Executable('MyScript.py', base=base)]
include_files = ['MyFolder1/','MyFolder2/Spreadsheet.xls']
setup(name='My Script',
version='0.1',
description='My Script',
executables=executables,
options = {'build_exe': {'includes':includes,
'packages':packages,
'include_msvcr':True,
'include_files':include_files}})
So far, I have tried listing both 'pythoncom' and 'win32com' in both the includes and the packages lists. Any help is greatly appreciated!
I had exactly the same issue when using pyinstaller to pack py into executable. Tried everything, but find out the issue is hidden in pyinstaller version. I was using pyinstaller 4.7 but when downgrade into 3.6, the exe works flawlessly.
Looking at the code, it looks like you need to ensure that a file called something like pythoncom33.dll is copied into the build directory.
So the whole problem actually stemmed from having the 32-bit version of pywin32 installed while running 64-bit versions of Python-3.3.2 and Windows 7. After adding pythoncom33.dll to the include_files of my setup.py as Thomas K had suggested, I got another error:
ImportError: DLL load failed: %1 is not a valid Win32 application
After some research, I found that this error is typical when mixing 32-bit and 64-bit. So I uninstalled pywin32 32-bit and installed pywin32 64-bit but my script threw yet another error:
import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found.
As suggested in this post, I copied the 28 win32*.pyd files from the Lib/site-packages/win32 folder to the Python33 folder right next to python.exe , and everything worked.
Add this to the top of your main.py:
import pywintypes
import win32api
seeļ¼š
PyWin32 and Python 3.8.0
So I ran into a similar problem where cx_Freeze was failing to pull in the pywintypes DLL, but frustratingly enough it was only on some machines which compelled me to explore the issue a bit further (I have a bad habit of chasing rabbits down holes). It seems that pywin32 tries to install its DLLs into a Windows system directory, but if that fails due to a lack of privileges it will fallback to placing them in your Python directory instead. The behavior I was seeing was a result of the fact that cx_Freeze applies a blacklist of well-known system folder paths against the collection of dependencies it has discovered in order to avoid pulling in operating system DLLs.
Copying these DLLs as needed by adding a path to them to the "include_files" parameter will indeed address the issue (just remember that you can't guarantee that they will be placed in the system folder). An alternative solution is to override the blacklist with a whitelist which you can configure using the "bin_includes" / "bin_path_includes" parameters. Here is a quick example that shows how to configure this parameter using a setup.py file (for Python 2.7, but the only difference should be the pywintypes DLL filename):
from cx_Freeze import setup, Executable
# This can also be an absolute path to the file if you wish to be very specific
bin_includes = ["pywintypes27.dll"]
options = {
"build_exe": {
"bin_includes": bin_includes
}
}
executable = Executable(script='main.py')
setup(version='x.x.x',
options=options,
executables=[executable])
Update pyinstaller related vision.
python -m pip install pyinstaller==3.6

Resources