ImportError in Compiled exe, but not in the script - python

I wrote a small python script that interacts with the database. I wanted to create an exe of the script file and then send it to the end user instead of sending the script file itself. I am using pytoexe to create the exe file .
This is how my setup.py file looks like now
from distutils.core import setup
import py2exe
setup(
console=["Test.py"],
zipfile = None,
data_files=[("",
["config.xml"]),
],
name='Test',
version='1.0.0',
url='',
license='',
author='test user',
author_email='',
description='',
#package_dir = {'': 'Lib'},
py_modules =['pyodbc']
#packages = ['pyodbc']
)
I run the script using the following command line
python setup.py py2exe --bundle 2
While creating the exe , py2exe displays this message
The following modules appear to be missing
['ElementC14N', 'pyodbc']
However the exe is generated. Now, whenever I run this exe , i get this message
Traceback (most recent call last):
File "Test.py", line 4, in
ImportError: No module named pyodbc
The script that I have runs fine if i execute the script. Its only that when i create the exe , the exe does not work and gives me this message .
Any help would be appreciated .
Note :
I have the following imports in the script file
import xml.etree.ElementTree as ET
import pyodbc
The other error ["ElementC14N"] that is present while py2exe is generating is the exe, I believe is due to the xml file that I am reading settings from. any help to resolve that issue would be praiseworthy as well .
Thanks

thank you all ....
this is what i did and it started working for me
options = {"py2exe":{"packages":"encodings",
"includes":["pyodbc",
"datetime", "decimal"],
"bundle_files":2,
"optimize":2},},

Related

Pyinstaller Not Adding Imports Correctly [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.

ImportError When Using cx_Freeze On a Script The Includes ffpyplayer

I successfully froze a Python 3.6 script with cx_Freeze v5.1.1. Then I added a new capability to the script by adding MediaPlayer from the ffpyplayer package and the script works perfectly. But when I freeze the new script, I receive an error "from ffpyplayer.player import MediaPlayer ImportError: DLL load failed: The specified module could not be found."
The import statement in my application script is
from ffpyplayer.player import MediaPlayer
From other posts, I have tried adding both ffpyplayer and ffpyplayer.player to the packages statement in the cx_Freeze setup.py script (in separate attempts) to fix the problem. I also tried adding player.cp36-win_amd64.pyd to the include statement in setup.py, but I still got the same error message.
cx_Freeze copied all ffpyplayer files from site-packages into the exe.win-amd64-3.6\lib\ffpyplayer except the __pycache__ folder containing __init__.cpython-36.pyc. However, manually adding this folder to exe.win-amd64-3.6\lib\ffpyplayer\ and to exe.win-amd64-3.6\lib\ffpyplayer\player\did not fix the issue (same error message).
Here is a minimal version of the setup.py file that cx_Freeze uses:
from cx_Freeze import setup, Executable
d = "C:\\Users\\Slalo_000\\Dropbox\\Python36Scripts\\AddtoBuild\\"
exe=Executable(script="VSWv300.py", base = "Win32GUI", icon = d + "VSWiconLarge.ico")
includes=[]
excludes=[]
packages=["numpy", "cv2", "ffpyplayer"]
setup(
version = "2.0.0.0",
description = "appName",
author = "me",
author_email = "",
name = "appName",
options ={'build_exe'{'excludes':excludes,'packages':packages,'include_files':includes}},
executables = [exe]
)
EDIT: The full error message traceback is:
File “C:\Users\slalo_000\AppData\Local\Programs\Python\Python36\lib\site-packages\cx_Freeze\initscripts\__startup__.py”, line 14, in run module.run()
File “C:\Users\slalo_000\AppData\Local\Programs\Python\Python36\lib\site-packages\cx_Freeze\initscripts\Console.py”, line 26, in run exec(code, m.__dict__
File “VSWv300.py”, line 20, in <module>
File “C:\Users\slalo_000\AppData\Local\Programs\Python\Python36\lib\site-packages\ffpyplayer\player\__init__.py”, line 10, in <module> from ffpyplayer.player.player import MediaPlayer
ImportError:DLL load failed: The specified module could not be found.
Any suggestions?

Issue with plyer library of python when creating a executable using pyinstaller

I am trying to generate a notification in windows using plyer library in python. It works fine when the python script is run. But when I try to create an executable file using pyinstaller and run the executable I keep getting this error
Traceback (most recent call last):
File "site-packages\plyer\utils.py", line 96, in _ensure_obj
ModuleNotFoundError: No module named 'plyer.platforms'
Traceback (most recent call last):
File "in_time.py", line 131, in <module>
File "site-packages\plyer\facades\notification.py", line 84, in notify
File "site-packages\plyer\facades\notification.py", line 90, in _notify
NotImplementedError: No usable implementation found!
This is the snippet of the code
from plyer import notification
notification.notify(
title='9 hours Completed',
message='You have successfully completed 9hrs for the day',
app_name='In Time App',
app_icon='Time3.ico'
)
When creating the executable with pyinstaller, add this to the command:
--hidden-import plyer.platforms.win.notification
I am using Windows and the solution with hiddenimports didn't work for me.
There's an other solution by copying the plyer package from python site_packages to the application directory as described here:
https://stackoverflow.com/a/64448486/11362192
The copying of this package can also be automated. To do this, add the original path to the plyer package as datas to the spec file:
site_packages_dir = 'C:/Python/Python310/Lib/site-packages/'
a = Analysis(
...
datas=[(site_packages_dir+'plyer', './plyer')],
...
add following hidden import to spec file
a = Analysis(
...
hiddenimports=['plyer.platforms.win.notification'],
...
pyinstaller --onefile --hidden-import plyer.platforms.linux.notification filename.py
if you are using linux
plyer.platforms.win.notification
if you are using win
There are also ios, macos, android platforms available so if you are using that, you may want to use those. If it doesn't work then you may want to check the plyer.platforms.<your_flatform> directory and see if notifications.py is existing or not.

py2app will not include PySide modules

Simple hello world QT python script. Works fine from the command line. When I package it i get:
Traceback (most recent call last):
File "/Users/jquick/bin/dist/gui.app/Contents/Resources/__boot__.py", line 340, in <module>
_run('/Users/jquick/bin/gui.py')
File "/Users/jquick/bin/dist/gui.app/Contents/Resources/__boot__.py", line 336, in _run
execfile(scriptpath, globals(), globals())
File "/Users/jquick/bin/gui.py", line 3, in <module>
from PySide.QtCore import *
ImportError: No module named PySide.QtCore
2012-06-02 00:23:04.823 gui[4835:707] gui Error
So it sounds like its not including the module.. but ive tried including it in both the setup.py and the command line. nothing works :(
setup.py:
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['gui.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True, 'includes': ['PySide.QtCore', 'PySide.QtGui']}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
i've tried creating with both the --alias option and without. Even tried labeling them as packages. But nothing I do seems to include them.
Can Python find PySide.QtCore? At the command line type:
from PySide.QtCore import *
If (1) works then make sure the Python version your invoking when executing py2app at the command line is the same Python version you're using at step (1). Some operating systems such as Mac OS X come installed with an older version of Python, and if your application works correctly when invoking it at the command line, then be sure you're not invoking a totally different version of python when trying to build your app.

PyInstaller: "ImportError: No module named os"

I'm trying to learn PyInstaller. I created two simple files, Test.py:
import os
and Test.spec:
anal = Analysis (["Test.py"])
pyz = PYZ(anal.pure)
exe = EXE(anal.scripts, pyz, name="Test.exe", exclude_binaries=1, debug=1)
coll = COLLECT(exe, anal.binaries, name="dist")
Then I ran:
Build.py Test.spec
This ran without any error mesages, and produced a directory dist with several files, including Test.exe. When I ran Test.exe, it failed with the output:
Found embedded PKG: C:\Documents and Settings\Rade\My Documents\Development\Test\Test.exe
Extracting binaries
manifestpath: C:\Documents and Settings\Rade\My Documents\Development\Test\Test.
exe.manifest
Error activating the context
python27.dll
Manipulating evironment
PYTHONPATH=C:/Documents and Settings/Rade/My Documents/Development/Test
importing modules from CArchive
extracted iu
extracted struct
extracted archive
Installing import hooks
outPYZ1.pyz
Running scripts
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named os
RC: -1 from Test
OK.
I'm sure I have made some stupid beginner's mistake, but what?
For simple files like this, you should use Makespec.py for creating spec's instead of writing manually. For large projects, you could use the Makespec.py's output as a template and edit them.
http://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html#create-a-spec-file-for-your-project

Categories

Resources