Executable created via PyInstaller crashes - python

I created a small app to download youtube videos and add them to my music folder so I can listen to them via spotify, app works fine as long as I run it via IDE.
I created an .exe file via pyinstaller, however it crashes on launch, I tried running it as administrator and also tried running it via cmd as people suggested in other threads, but nothing works.
I created it by using:
pyinstaller --onefile -c test.py
This is the python code:
from pytube import YouTube
from pytube import Playlist
from moviepy.editor import *
from pathlib import Path
import os
url = input('Enter URL: ')
ytd = YouTube(url)
stream = ytd.streams.first().download(filename= 'video') #stiahne do root filu
mp3_file = ytd.title + '.mp3' #meno pesnicky
#videoClip = VideoFileClip('video.mp4')
audioClip = VideoFileClip('video.mp4').audio
audioClip.write_audiofile(mp3_file) #mp4 na mp3
audioClip.close()
VideoFileClip('video.mp4').close() #v root file je mp3 a mp4
os.remove('video.mp4') #zmaze mp4, ostane mp3
file_path = str(os.path.dirname(os.path.realpath(mp3_file))) + '\\' + mp3_file
music_path = str(os.path.join(Path.home(), "Music")) + '\\' + mp3_file
Path(file_path).rename(music_path)
This is what I get one I try to run it via cmd:
Traceback (most recent call last):
File "C:\Users\rporu\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\PyInstaller\loader\rthooks\pyi_rth_pkgres.py", line 13, in <module>
import pkg_resources as res
File "c:\users\rporu\appdata\local\programs\python\python38-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.__dict__)
File "site-packages\pkg_resources\__init__.py", line 86, in <module>
ModuleNotFoundError: No module named 'pkg_resources.py2_warn'
[3296] Failed to execute script pyi_rth_pkgres

while creating exe use the hidden import
pyinstaller --hidden-import=pkg_resources.py2_warn --onefile -c test.py

Related

QPython on mobile won't allow the OS module to write an mp4 file to the sd card from PyTube

The code:
from pytube import YouTube
import os
def video():
yt = YouTube(input("URL: "))
yd = yt.streams.get_highest_resolution()
download_path = os.path.join("/storage/24C4-107D/Unsorted", yt.title)
yd.download(download_path)
print("Done!")
while True:
video()
When I run it it returns the error:
/data/user/0/org.qpython.qpy3/files/bin/qpython3-android5.sh /storage/emulated/0/qpython/scripts3/.last_tmp.py && exit
u0_a179#klimtwifi:/ $ /data/user/0/org.qpython.qpy3/files/bin/qpython3-android5.sh /storage/emulated/0/qpython/scripts3/.last_tmp.py && exit
URL: https://www.youtube.com/watch?v=GJY8OMJXRAk
Traceback (most recent call last):
File "/storage/emulated/0/qpython/scripts3/.last_tmp.py", line 11, in <module>
video()
File "/storage/emulated/0/qpython/scripts3/.last_tmp.py", line 8, in video
yd.download(download_path)
File "/data/user/0/org.qpython.qpy3/files/lib/python3.6/site-packages/pytube/streams.py", line 301, in download
filename_prefix=filename_prefix,
File "/data/user/0/org.qpython.qpy3/files/lib/python3.6/site-packages/pytube/streams.py", line 349, in get_file_path
return os.path.join(target_directory(output_path), filename)
File "/data/user/0/org.qpython.qpy3/files/lib/python3.6/site-packages/pytube/helpers.py", line 254, in target_directory
os.makedirs(output_path, exist_ok=True)
File "/data/user/0/org.qpython.qpy3/files/lib/python36.zip/os.py", line 220, in makedirs
PermissionError: [Errno 13] Permission denied: '/storage/24C4-107D/Unsorted/High Hopes'
I have the pytube module installed and the code runs on my windows machine, but when run on android in QPython it no longer works.
I have tried reinstalling the modules, and as far as i believe OS is built in to to QPython.

Pyinstaller : .exe file doesn't work the same way as in IDE

I have written a python script, using eel for the GUI, that converts & does some calculations on files in a folder. For this, i am using a python library called asammdf. The code works well in an IDE but when i use pyinstallerand create a .exe file the code doesn't seem to work the same way.
import eel
from pathlib import Path
from asammdf import MDF
from pathlib import Path
import glob
import sys
import os
from datetime import timedelta
eel.init("path\to\folder\Python")
def python_code():
# a python script that uses asammdf
#eel.expose
I have tried copying the asammdf directory into the python folder and pyinstaller seems to include it in the .exe dist folder but still it doesn't work. Can anyone help me out please?
The error message comes as --
asammdf\mdf.py:4597: UserWarning: The argument `ignore_invalid_signals` from the method `extract_bus_logging` is no longer used and will be removed in the future
Traceback (most recent call last):
File "eel\__init__.py", line 281, in _process_message
File "converterrxd_csv.py", line 79, in pythoncode
File "asammdf\mdf.py", line 4625, in extract_bus_logging
File "asammdf\mdf.py", line 4666, in _extract_can_logging
File "asammdf\blocks\utils.py", line 1807, in load_can_database
File "canmatrix\formats\__init__.py", line 71, in loadp
File "canmatrix\formats\__init__.py", line 86, in load
KeyError: 'canmatrix.formats.dbc'
I tried installing the can-matrix package as well but that doesn't solve the problem.
You need to add the hidden import for canmatrix
see https://github.com/danielhrisca/asammdf/blob/180a1588737ae7aaf367aaa8fd1c81aff616df16/asammdf.spec#L37

pyinstaller not creating a shortcut for pygame [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.

pyinstaller --onefile argument doesn't work with pygame [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.

rpy2 is working fine in console but not working in executable file

i'm using rpy2 in spyder 4. all commands are working fine in console. i created an executable with pyinstaller and i got this error in exe file.
Traceback (most recent call last):
File "kopa.py", line 12, in <module>
ModuleNotFoundError: No module named 'rpy2'
[13148] Failed to execute script kopa
I will give an example to be short;
import os
os.environ['R_HOME'] = 'C:/Program Files/R/R-3.6.3'
os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/Lib/site-packages/rpy2'
import rpy2.robjects as ro
ro.r("x=c(1,2,3,4,5)")
ro.r("y=c(11,12,13,14,15)")
ro.r("z=mean(x)+mean(y)")
print(ro.r("z"))
all working fine in console. when i create executable file then i'm getting the above error. where is the problem?

Categories