TypeError after converting python game to executable [duplicate] - python-3.x

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.

Related

Problem with SQLite3 and python using Pyinstaller

I've been writting some code to create an easy app to register products using python 3.7.3 and sqlite3 on debian. When I'm finally done, I tried to create an executable file from my script using pyinstaller. Everything was fine until I run the executable file by command using "./file" in the dist folder and there were 3 errors. On my sqlite database I used just a table called "product" but the terminal shows me:
sqlite3.OperationalError: no such table: product
Additionally it shows me other messages:
Traceback (most recent call last):
File "index.py", line 141, in <module>
File "index.py", line 47, in __init__
File "index.py", line 61, in get_products
File "index.py", line 52, in run_query"
On terminal I used this command to run pyinstaller :
pyinstaller --add-data "database.db:." index.py --onefile
Why my database is not recognized to run as onefile?
You can see my code on https://github.com/BraymNoodles/AppPythonProducts.git
When you run the executable, it will decompress itself to a path like _MEIxxxxx (where xxxxx is a random number) inside temporary path (environment variable TEMP). The file database.db is within that directory.
So if your code opens the database file like below:
conn = sqlite3.connect('database.db')
It will look for database.db in current directory, but it does not exist. So a new database.db will be created and this causes the error mentioned in your question:
sqlite3.OperationalError: no such table: product
because database.db is empty.
You need to get the temporary path by using below code:
import os
import sys
...
appdir = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
and open the database like below:
conn = sqlite3.connect(os.path.join(appdir, 'database.db'))
You can read more information about the temporary path in PyInstaller document.
base_path = os.path.dirname("**sys.executable**")
conn sqlite3.connect(os.path.join(base_path, 'database.db')
Use this if you are trying to connect sqlite3 to a one file executable with no console.

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.

cx_Freeze converted exe: window closes immediately

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")])

Pyinstaller does not look for the file inside the Python Virtual Environment

I want to convert Python code into standalone executable , the code uses numpy, scipy, and Pymc3 modules. I am using Python 3.6.4. I have created the project using Virtual Environment in Pycharm IDE. The command that I used to run pyinstaller is as follows:
venv/Scripts/pyinstaller --onefile src/POD.py
venv being the folder where virtual environment is stored and src being the folder where my Python source code ie. POD.py is saved. Pyinstaller runs just fine generates some warning message, but when I try to run the executable generated by pyinstaller it thrown as error
Traceback (most recent call last):
File "POD.py", line 196, in <module>
File "POD.py", line 79, in train
File "Lib\site-packages\theano\tensor\var.py", line 155, in __mul__
File "Lib\site-packages\theano\gof\op.py", line 615, in __call__
File "Lib\site-packages\theano\tensor\elemwise.py", line 482, in make_node
File "Lib\site-packages\theano\tensor\elemwise.py", line 438, in get_output_info
File "Lib\site-packages\theano\tensor\elemwise.py", line 157, in __init__
File "Lib\site-packages\theano\gof\op.py", line 1308, in __init__
File "Lib\site-packages\theano\gof\op.py", line 1331, in load_c_code
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\User\\AppData\\Local\\Temp\\_MEI126642\\theano\\tensor\\c_code\\dimshuffle.c'
[4756] Failed to execute script POD
Seems like it is trying to find the file dimshuffle.c outside of the virtual environment. In-fact the I can see that there is folder inside virtual environment which has the dim_shuffle.c code. I can find it inside virtual environment in following folder.
venv/Lib/site-packages/theano/tensor/c_code/dimshuffle,c
My question is how do I instruct pyinstaller to look for dimshuffle inside virtual environment folder?
You can,
extend the sys.path by editing the spec file.
pyi-makespec --paths=/path/to/thisdir \
--paths=/path/to/otherdir myscript.py
List the hidden imports using the spec file.
for more info refer this

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