Can not run exe packed by pyinstaller - python

I use windows 10 and python2.7.
I have use PyInstaller to pack a program into exe. But I can not run the .exe file.
error:
raise FileNotFoundError('Tcl data directory "%s" not found.' % (tcldir))
IOError: Tcl data directory "C:\Users\test\AppData\Local\Temp\_MEI10~1\tcl" not
found.
[4072] Failed to execute script pyi_rth__tkinter

That's python error which means your program is running.
Check your code to see why it does not find the file you are mentioning.
Note: If you use relative paths consider that it matters where the .exe file is executed.
This is the process home directory.

You should use the following command:
pyinstaller main.py --add-data 'tcl;./tcl' #linux separator use 'tcl:./tcl'
Note: left 'tcl' is in the main.py's directory, right 'tcl' is target directory which is exe genrated directory. if right 'tcl' not existing will be created!

Related

After compiling a python script to EXE the Archive method doesn't work

I have a python script that I compiled to an EXE, one of the purposes of it is to extract a 7z file and save it to a destination.
If I'm running it from PyCharm everything works great, this is the code:
def delete_old_version_rename_new(self):
winutils.delete(self.old_version)
print("Extracting...")
Archive(f"{self.new_version}_0.7z").extractall(f"{self.destination}")
print("Finished")
os.rename(self.new_version, self.new_name)
I used pyinstaller to compile the program and used to command pyinstaller --onefile --paths {path to site packages} main.py
Thanks!
Single-file executables self-extract to a temporary folder and run from there, so any relative paths will be relative to that folder not the location of executable you originally ran.
My solution is a code snippet such as this:
if getattr(sys, 'frozen', False):
app_path = os.path.dirname(sys.executable)
else:
app_path = os.path.dirname(os.path.abspath(__file__))
which gives you the location of the executable in the single-file executable case or the location of the script in the case of running from source.
See the PyInstaller documentation here.
Eventually i just used a 7z command line i took from https://superuser.com/questions/95902/7-zip-and-unzipping-from-command-line
and used os.system() to initialize it.
Since my program is command line based it worked even better since its providing a status on the extraction process.
Only downside is i have to move the 7z.exe to the directory of my program.

Pyinstaller failed to execute script: FileNotFoundError: No file or directory: 'C:\\Users\\etc'

I have a python file I am converting to exe via Pyinstaller. The coversion runs fine with no error, however when I run the exe file I get error in line 13 of the python file (line is import librosa). Then I get a bunch of files and then a
FileNotFoundError: No file or directory: 'C:\\Users\\johnny\\Appdata\\Local\\Temp\\_MEI70722\\librosa\\util\\example_data\\registry.txt'.
Also the python file itself runs fine.
Any help would be appreciated
PyInstaller tries to find all the dependencies, however this file is not imported but loaded so it misses it. You can simply force it to add it:
--add-data [path to your python]/Lib/site-packages/librosa/util/example_data;librosa/util/example_data
With The full command be like :
pyinstaller --onefile [YourScript].py --add-data [path to your python]/Lib/site-packages/librosa/util/example_data/registry.txt;librosa/util/example_data
You'll need to specify the data files as PyInstaller hooks.
Create a folder "extra-hooks", and in it a file "hook-librosa.py"
paste these 2 lines in "extra-hooks/hook-librosa.py":
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('librosa')
Then tell PyInstaller where to locate this file with adding 1 of the following to your PyInstaller command:
--additional-hooks=extra-hooks
--additional-hooks-dir "[PATH_TO_YOUR_PROJECT]/axtra-hooks"
The 2nd one worked for me, and I was using auto-py-to-exe, built on PyInstaller.
I guess the file doesn't exist. Open a file manager and copy the directory.
In the PyInstaller, you should type in the python file's name and then --onefile. It makes an .EXE file (if you are on windows) with all the imported files within. You can learn more here: https://pyinstaller.readthedocs.io/en/stable/usage.html

Trying to compile a .mp3 + .py files into one executable [duplicate]

I'm struggling with pyinstaller. Whenever I build this specific script with a kivy GUI and a .kv file, and run the .exe after the build, I get a fatal error:
IOError: [Errno 2] No such file or directory: 'main.kv'
I've tried adding the .kv file, as well as a mdb and dsn file (for pypyodbc) using --add-data, but I get an error: unrecognized arguments: --add-data'main.kv'. (There were more --add-data arguments for the other files mentioned.)
Are there any solutions for this or maybe alternative methods?
As others (#Anson Chan, #schlimmchen) have said:
If you want to add some extra files, you should use Adding Data Files.
Two ways to implement
Command Line: add parameter to --add-data
Spec file: add parameter to datas=
Generated when running pyinstaller the first time.
Then later you can edit your *.spec file.
Then running pyinstaller will directly use your *.spec file.
Parameter Logic
Parameter in --add-data or datas=:
--add-data:
format: {source}{os_separator}{destination}
os_separator:
Windows: ;
Mac/Linux/Unix: :
source and destination
Logic:
source: path to single or multiple files, supporting glob syntax. Tells PyInstaller where to find the file(s).
destination
file or files: destination folder which will contain your source files at run time.
* NOTE: NOT the destination file name.
folder: destination folder path, which is RELATIVE to the destination root, NOT an absolute path.
Examples:
Single file: 'src/README.txt:.'
multiple files: '/mygame/sfx/*.mp3:sfx'
folder: '/mygame/data:data'
datas=
Format: list or tuple.
Examples: see the following.
added_files = [
( 'src/README.txt', '.' ),
( '/mygame/data', 'data' ),
( '/mygame/sfx/*.mp3', 'sfx' )
]
a = Analysis(...
datas = added_files,
...
)
Your case
For your (Windows OS) here is:
--add-data in command line
pyinstaller -F --add-data "main.kv;." yourtarget.py
OR:
datas= in yourtarget.spec file, see following:
a = Analysis(...
datas = ["main.kv", "."],
...
)
If you check pyinstaller -h for help, you can find --add-data option works like this [--add-data <SRC;DEST or SRC:DEST>]. So in your case try
pyinstaller -F --add-data "main.kv;main.kv" yourtarget.py
The solution is to run: pyi-makespec yourscript.py
Then edit the yourscript.spec script and add the files under datas in a= Analysis.
datas=[ ( '/pathToYourFile/main.kv', '.' )]
then run pyinstaller yourscript.spec
should be good after that.
Next -F or --onefile option is assumed when running pyinstaller.
Note that (MacOS Monterey, 12.2 here) the expected folder hierarchy w/in you .app file will be similar to this,
pyinstaller does not add files nor create necessary folders into any of the folders of this folder structure; at least not in any apparent way. You won't find them.
However, when the application runs, a temporary folder is used under /var/folders which is very different from the folder structure in point 1. above. print(os.path.dirname(__file__)) while running the application will reveal which exact temporary folder is used each time it runs. For convenience, let's call it my_app_tmp_folder i.e. your app runs under the folder /var/folder/my_app_tmp_folder
Then, pyinstaller adds data files or creates necessary directories w/in this temporary folder. In other words, when the application runs, all added files will be there and according to the specified folder structure (through --add-data option). print(os.listdir(os.path.dirname(__file__))) will show system and application needed files and folders.
Bottom line: Files specified w/ --add-data option will be visible w/in /var/folder/my_app_tmp_folder when running and not w/in the *.app folder.
Some useful links from documentation:
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#using-file
https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-files-to-the-bundle
https://pyinstaller.readthedocs.io/en/stable/operating-mode.html#bundling-to-one-file
My application had this issue and a subsequent issue that is likely, if not inevitable.
1. --add-data for a kv file
Use --add-data as in the answer by crifan.
2. Kivy still can't find the file
Once PyInstaller has the kv file in the correct directory, Kivy still can't find the file.
Possible Symptoms:
GUI launches, but screen is black and empty.
An AttributeError error that depends on the application code.
AttributeError Examples:
This question
My own case:
AttributeError: 'NoneType' object has no attribute 'ids'
Fortunately, this answer solves the problem.

Python can't run absolute script?

I encountered such a weird situation:
naivechou#naivechou/~>python test.py
test
naivechou#naivechou/~>pwd
/home/naivechou
naivechou#naivechou/~>python /home/naivechou/test.py
C:\toolchain\python\python.exe: can't open file '/home/naivechou/test.py': [Errno 2] No such file or directory
My working directory is /home/naivechou/, test.py is in there.
If I run test.py with absolute path, I'll get an error message of No such file or directory.But everything will be fine if I enter that directory and then run it. What's wrong with python?
Try moving into the folder where the python script is located and do a "ls" command there in Linux. if windows then do 'dir'. if you see the required file there then execute the following command
C:\location_where_the_script_is> python yourfile.py
For commands entered on the command line, Windows doesn't recognize forward-slashes as directory separators.
Your second example is looking in the current directory for the literal filename /home/naivechou/test.py, and of course such a filename does not exist.
Use backslashes instead, as is the Windows way:
python \home\naivechou\test.py

PyInstaller cannot add .txt files

I'm fairly new with programming (and with Python) and the Stack Overflow question/response system allowed me to resolve all my problems until now. I didn't find any post directly addressing my current issue, but have to admit that I don't really know what's wrong. Let me explain.
I'm trying to make an executable file of a *.py script using PyInstaller. There's no problem doing it with a simple Python script (using --onefile), but it does not work when it comes to a more complex program that uses other *.py and *.txt files. I know that I need to modify the specification file and tried many alternatives - adding hidden files for instance.
Here are the files:
UpdatingStrategy.py (the target file to transform in executable)
LPRfunctions.py (UpdatingStrategy.py imports functions from this file)
The following *.txt files are read by UpdatingStrategy.py:
Strategy_Observ.txt
Strategy_Problems.txt
Updating_Observ1.txt
Updating_Observ2.txt
Updating_Problems.txt
I'm using Python 3.5 and Windows 10. Tell me if you need extra information.
How do I use the specification file properly and modify it in order to make an executable file of UpdatingStrategy.py?
I have read the PyInstaller documentation, but I lack many key principles and I couldn't make it work.
After the line
a = Analysis( ... )
add
a.datas += [
("/absolute/path/to/some.txt","txt_files/some.txt","DATA"),
("/absolute/path/to/some2.txt","txt_files/some2.txt","DATA"),
("/absolute/path/to/some3.txt","txt_files/some3.txt","DATA"),
]
Then in your program use the following to get the resource path of your .txt files.
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.environ.get("_MEIPASS2",os.path.abspath("."))
return os.path.join(base_path, relative_path)
...
txt_data = open(resource_path("txt_files/some.txt")).read()
Make sure you build it like python -m PyInstaller my_target.spec ... do not call PyInstaller directly against your .py file after you have edited your specification file or it will overwrite your edited file...
Anyone reading this in 2021... I've just run into similar issue with Pyinstaller. Needed to add a text file to my python code:
pyinstaller --add-data "/my/path/to/mytextfile.txt:/path/mytextfile.txt" mypython.py --onedir or --onefile
No matter if onedir or onefile, my code just never found the text file. Infact it threw the error:
IsADirectoryError: [Errno 21] Is a directory: /path/mytextfile.txt
Which didn't make sense to me because that's a file not a folder. Only when I checked this with the --onedir flag and I followed the path, I realized that pyinstaller would not only create a folder path, but also folder mytextfile.txt and put mytextfile.txt in there... so really the --add-data flag only wants a destination folder not the path to the file.
pyinstaller --add-data "/my/path/to/mytextfile.txt:path" mypython.py
or in the spec file i.e mypython.spec
datas=[('/my/path/to/mytextfile.txt', 'path')]
Should fix this. Note also the "DATA" configuration in the spec file is gone.

Categories

Resources