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
I have generated an executable file from a python file using pyinstaller. The program works how it is supposed to work but there is this warning message it appears in the window that I would like to hide.
The following line does suppress all warning messages when the python file is run within the IDE.
warnings.filterwarnings('ignore')
But in the window of the executable file, this warning is displayed:
\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py:627: MatplotlibDeprecationWarning:
The MATPLOTLIBDATA environment variable was deprecated in Matplotlib 3.1 and will be removed in 3.3.
exec(bytecode, module.__dict__)
If you are going to using a customized spec building file, you can just add following line to your spec files to suppress these startup warnings(according to https://pyinstaller.readthedocs.io/en/stable/spec-files.html#giving-run-time-python-options):
exe = EXE(pyz,
a.scripts,
[('W ignore', None, 'OPTION')],
# ...
Since a spec file is actually a python script, you can replace pathex with os.getcwd() and make sure you've already import os module in your spec file.
I've tried on Windows 10 with Python 3.7.4 and pyinstaller 3.5. It works!
Since you've provided a customized spec file, your basic building command should change to:
pyinstaller xxx.spec
Please let me know if it works.
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.
I am trying to package my project code into a an executable binary using Cython and PyInstaller libraries.
My code directory looks like this:
The main.py is the main code which imports the logic from program_a.py and program_b.py.
I am successfully able to convert my program_a and program_b files into .so files which can be imported by any python code. I did this by executing the following script.
from distutils.core import setup
from Cython.Build import cythonize
sourcefiles = ['program_a.py', 'program_b.py']
setup(
name = "Hello World",
ext_modules = cythonize(sourcefiles),
)
By executing >python setup.py build_ext --inplace I get .so files as shown below
When I run python main.py it runs perfectly with .so files. Which shows that I can import them as a module.
Now, I want to package binaries (.so) files and main.py into single binary file. For that I used the following command provided by pyInstaller
pyinstaller "main.py" --onefile
It actually gives a binary in dist/ folder but I cannot able to import some modules and getting the following error:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import program_a as lisence_checker
File "program_a.py", line 1, in init program_a
ModuleNotFoundError: No module named 'licensing'
[18032] Failed to execute script main
How can I link libraries with the pyinstaller or embed library information into my binaries?
What I found yet:
Building Cython-compiled python code with PyInstaller
https://riptutorial.com/cython/example/21982/bundling-a-cython-program-using-pyinstaller
But all of these above links are not using any external package inside there python code examples. I am able to compile the code without external modules
After getting familiar with PyInstaller package I am able to figure out the issue. I followed the following steps to make it work for me at the end.
Now, posting my answer to help others :)
## Build *.so files from python modules
1. Execute "setup.py" file
> python setup.py build
2. It will generate "*.so" modules inside "build/lib.linux-x86_64-3.6" dir.
## Created binary from cython modules
1. Copy the binaries (i.e. *.so) files into binary folder
2. Get inside the binary folder 'cd binary'
3. Run Pyinstaller command inside binary directory: `python -O -m PyInstaller --clean --onefile idps.spec`
4. Your binary will be inside dist folder 'binary/dist/'
5. Execute the binary in linux using './dist/sample_app'
6. Your app is ready :)
Here is spec file to make it work for me:
# -*- mode: python -*-
block_cipher = None
a = Analysis(['main.py'],
pathex=['cython_pyinstaller_sample/binary'],
binaries=[('program_a.cpython-36m-x86_64-linux-gnu.so', '.'),('program_b.cpython-36m-x86_64-linux-gnu.so', '.')],
datas=[('config_file.txt', '.')],
hiddenimports=['licensing', 'licensing.methods', 'pandas'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False) pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher) exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='sample_app',
debug=True,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
Just in case someone's looking for a quick fix.
I ran into the same situation and found a quick/dirty way to do the job. The issue is that pyinstaller is not adding the necessary libraries in the .exe file that are needed to run your program.
All you need to do is import all the libraries (and the .so files) needed into your main.py file (the file which calls program_a.py and program_b.py). For example, assume that program_a.py uses opencv library (cv2) and program_b.py uses matplotlib library. Now in your main.py file you need to import cv2 and matplotlib as well. Basically, whatever you import in program_a.py and program_b.py, you have to import that in main.py as well. This tells pyinstaller that the program needed these libraries and it includes those libraries in the exe file.
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},},
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