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

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

Related

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.

Jupyter Extension Installation Failed: Error says 'terminado' wasn't found, but I should already have it

I've tried to install jupyter extensions following the instruction here.
The first step named 'Install the python package' in the instruction was succeeded.
But the second one named 'Install javascript and css files' was failed.
I executed jupyter contrib nbextension install --user as instructed, but an error occured.
The error says: pkg_resources.DistributionNotFound: The 'terminado>=0.8.1' distribution was not found and is required by notebook. (All traceback shown is as below.)
But I confirmed that I've already installed 'terminado' v0.8.2 package, which was installed via pip.
How can I handle this problem? Is the problem solely that jupyter command does not know where the 'terminado' is installed? Or is the problem more serious?
All the error message is as below:
Traceback (most recent call last):
File "/usr/local/bin/jupyter-contrib", line 5, in <module>
from pkg_resources import load_entry_point
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module>
#_call_aside
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside
f(*args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 583, in _build_master
ws.require(__requires__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 900, in require
needed = self.resolve(parse_requirements(requirements))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'terminado>=0.8.1' distribution was not found and is required by notebook
I'm using macOS Catalina (but same problem appeared on Mojave.
Summary
The problem is, as it may be turned out with seeing the error message, that the jupyter contrib command uses python2, not python3 which is my preference.
Problem
The usage of python2 by the command was caused by the shebang of /usr/local/bin/jupyter-contrib file.
The shebang was #!/usr/bin/python, which means that it specified jupyter-contrib used python interpreter which located on /usr/bin/python which is python2 on my machine (and many other Mac machine, maybe).
Hence you should specify python3 with the shebang rather than python2.
Solution
First, get your python3 installation path like this:
$ which python3
Copy the returned path.
Open the /usr/local/bin/jupyter-contrib file. Note that this file is read-only but you have to rewrite it, so you should open it with sudo:
$ sudo vim /usr/local/bin/jupyter-contrib
Rewrite the shebang on the 1st line. Shebang may now be like this:
#!/usr/bin/python
where it specifies python2 as its interpreter. You should rewrite the path to python3's path which you copied at step 1:
#!{{Paste your python3's path}}
Save the file.
That's it.
Now jupyter-contrib uses python3.
So jupyter contrib nbextension install --user command should succeeds.

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

[ Python 2.7 ]Package program with Pynsist

I am packaging a Python 2.7 program with the lastest version of Pynsist.
I've created an installer.cfg file following this example.
But when I try to package my application running
pynsist installer.cgf
into the application folder it comes up with
Copying Python installer to build directory
PyLauncher MSI already in build directory.
Copying packages into build directory...
Traceback (most recent call last):
File "/usr/local/bin/pynsist", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 540, in main
InstallerBuilder(**args).run(makensis=(not options.no_makensis))
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 495, in run
self.prepare_packages()
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 381, in prepare_packages
py_version=self.py_version, exclude=self.exclude)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 224, in copy_modules
mc.copy(modname, target, exclude)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 195, in copy
check_package_for_ext_mods(path, self.py_version)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 41, in check_package_for_ext_mods
check_ext_mod(os.path.join(path, dirpath, filename), target_python)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 30, in check_ext_mod
raise ExtensionModuleMismatch(extensionmod_errmsg % ('Windows', path))
nsist.copymodules.ExtensionModuleMismatch: Found an extension module that will not be usable on Windows:
/usr/lib/python2.7/dist-packages/pygame/rwobject.so
Put Windows packages in pynsist_pkgs/ to avoid this.
So the problem I think is with Pygame.
On Google there in nothing about this, but i cannot use others programs for packaging(eg. py2exe, pyinstaller ecc...).
Thanks and sorry for the bad english
Reposting as an answer, since it worked:
If you put pygame in packages=, it tries to copy it from your computer. But on your computer that's pygame for Linux, which won't work on Windows. If you instead put pygame in the pypi_wheels= bit of the config file, Pynsist will take care of downloading a Windows version for you.
Have a look at the pygame example in the Pynsist repository.
Most packages don't have this problem because they only contain Python code, which is the same files on all platforms. Pygame has compiled modules, which have to be compiled for the right platform.

Resources