This question already has an answer here:
py2app-installed app using pygame fails
(1 answer)
Closed 1 year ago.
Title, I just finished my first pygame project which Is a very simple game with a main menu module and a main game module, they both run perfectly when I run them from sublime.
I tried using py2app to share this game with some friends, after installing py2app this is what I did in my terminal:
py2applet --make-setup MainMenu.py # (this module imports the main game module)
then I edited my setup.py file to include all my python files like images, sounds and fonts (this is the setup.py file):
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['MainMenu.py']
DATA_FILES = ['MySprite/Shoot/1.png','MySprite/Shoot/2.png',
'MySprite/Go/1.png','MySprite/Go/2.png','MySprite/Go/3.png','MySprite/Go/4.png','MySprite/Go/5.png','MySprite/Go/6.png','MySprite/Go/7.png','MySprite/Go/8.png',
'go_1.png','go_2.png','go_3.png','go_4.png','go_5.png','go_6.png','go_7.png','go_8.png','go_9.png','go_10.png','go_1L.png','go_2L.png','go_3L.png','go_4L.png','go_5L.png','go_6L.png','go_7L.png','go_8L.png','go_9L.png','go_10L.png','HomeScreen.png','icon.png','Bullet.png','SkyNight.png','GamePlatform.png','Heart.png','Starjedi.ttf','Chernobyl.ttf',
'MainMenu.wav','Fireball.wav','background.wav','Jump.wav','Zombie.wav','Hit.wav']
OPTIONS = {}
setup(
app = APP,
data_files = DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
Then back to my terminal:
rm -rf build dist
then:
python setup.py py2app -A
which gave me an error so I changed it to python3 and it created a "build" and a "dist" folders, I tried opening the app inside the "dist" folder but it gave me an error and asked me to terminate or open the console, I right clicked on it and pressed show package options --> contents --> MacOs and pressed the file which opened another terminal with the error:
screen_home = pygame.image.load('HomeScreen.png')
FileNotFoundError: No such file or directory.
Both modules run perfectly from sublime, Im out of ideas and I tried googling the problem and I can't find a solution, Im new at this so I apologize if the solution was obvious or it was a dumb question and id appreciate any help.
I don't have a real answer but a few things to try and check:
We need to review a few things in the two lines, sometimes the setup.py requires to have the full path where each file is located, it is the right way, otherwise the setup.py will not find where are those images and it won't be able to include them into the final package, Are all those files in the same folder?, even if they are, try to add the full path for each file (jbsidis should be replaced by your username):
import os
APP = ['/home/jbsidis/Escritorio/MainMenu.py']
if os.path.isfile(APP[0])==True:
print("the MainMenu.py file it does exists")
DATA_FILES = ['/home/jbsidis/Escritorio/MySprite/Shoot/1.png','/home/jbsidis/Escritorio/MySprite/Shoot/2.png','/home/jbsidis/Escritorio/MySprite/Go/1.png','/home/jbsidis/Escritorio/MySprite/Go/2.png','/home/jbsidis/Escritorio/MySprite/Go/3.png','/home/jbsidis/Escritorio/MySprite/Go/4.png','/home/jbsidis/Escritorio/MySprite/Go/5.png','/home/jbsidis/Escritorio/MySprite/Go/6.png','/home/jbsidis/Escritorio/MySprite/Go/7.png','/home/jbsidis/Escritorio/MySprite/Go/8.png','/home/jbsidis/Escritorio/go_1.png','/home/jbsidis/Escritorio/go_2.png','/home/jbsidis/Escritorio/go_3.png','/home/jbsidis/Escritorio/go_4.png','/home/jbsidis/Escritorio/go_5.png','/home/jbsidis/Escritorio/go_6.png','/home/jbsidis/Escritorio/go_7.png','/home/jbsidis/Escritorio/go_8.png','/home/jbsidis/Escritorio/go_9.png','/home/jbsidis/Escritorio/go_10.png','/home/jbsidis/Escritorio/go_1L.png','/home/jbsidis/Escritorio/go_2L.png','/home/jbsidis/Escritorio/go_3L.png','/home/jbsidis/Escritorio/go_4L.png','/home/jbsidis/Escritorio/go_5L.png','/home/jbsidis/Escritorio/go_6L.png','/home/jbsidis/Escritorio/go_7L.png','/home/jbsidis/Escritorio/go_8L.png','/home/jbsidis/Escritorio/go_9L.png','/home/jbsidis/Escritorio/go_10L.png','/home/jbsidis/Escritorio/HomeScreen.png','/home/jbsidis/Escritorio/icon.png','/home/jbsidis/Escritorio/Bullet.png','/home/jbsidis/Escritorio/SkyNight.png','/home/jbsidis/Escritorio/GamePlatform.png','/home/jbsidis/Escritorio/Heart.png','/home/jbsidis/Escritorio/Starjedi.ttf','/home/jbsidis/Escritorio/Chernobyl.ttf','/home/jbsidis/Escritorio/MainMenu.wav','/home/jbsidis/Escritorio/Fireball.wav','/home/jbsidis/Escritorio/background.wav','/home/jbsidis/Escritorio/Jump.wav','/home/jbsidis/Escritorio/Zombie.wav','/home/jbsidis/Escritorio/Hit.wav']
for x in DATA_FILES:
if os.path.isfile(x)==True:
print("the "+str(x)+" file it does exists")
else:
print("the "+str(x)+" DOES NOT Exists in that location and that's why you got the error with your setup.py")
Here is the image in my case, my folders don't have those files, so the result is:
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.
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
Error message from running my exe:
ModuleNotFoundError: No module named 'openpyxl'
testHi.py
#simple test to see if openpyxl module works
import openpyxl
print ("hi")
input()
hook-openpyxl.py
# taken from pyinstaller dev team, store in same dir as testHi.py
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('openpyxl')
cmd line input:
pyinstaller.exe --onefile --icon=py.ico --additional-hooks-dir=. hiTest.py
I run the the hiTest and get the error above.
I have looked everywhere for this solution. Can anyone tell me what I am doing wrong.
I fixed my issue by installing it through Pip, rather than install the package through Pycharm, and Pyinstaller was able to find the package.
I got the idea from looking through the text in the command prompt and saw it was loading modules that I had installed via Pip and not through Pycharm.
I was able to get this working using auto-py-to-exe (which uses pyinstaller) by including the following folders/files from my python library into the same folder that I run pyinstaller from:
jdcal.py
openpyxl (folder)
et_xmlfile (folder)
pyinstaller command:
pyinstaller -y -F "[directory]/myscript.py"
Notes on Library Location:
Windows library location for me was: C:\users[username]\AppData\Local\Programs\Python\Python37-32\Lib
The packages were in the "site_packages" folder
use
--hiddenimport openpyxl
long with the previous solutions, it worked for me, I was able to enforce the import of openpyxl.
You was quite close. :-)
I fixed the problem by modifying the "hook-openpyxl.py" file. The command collect_data_files('openpyxl') actually returns an empty list. But there is another command collect_submodules which seems to do what we want. So my "hook-openpyxl.py" file looks like this.
from PyInstaller.utils.hooks import collect_submodules
hiddenimports = collect_submodules('openpyxl')
I placed the "hook-openpyxl.py" file in the same directory like my spec file. In the spec file I set to location of the new hook file
a = Analysis(
...
...
hookspath=['.'],
...
...
...
I guess, you will have the same result with your command line parameter
pyinstaller.exe --onefile --icon=py.ico --additional-hooks-dir=. hiTest.py
My environment
Python=3.8
openpyxl=3.0.10
PyInstaller=4.8
This is my project structure. I use virtualenv in my project but when I run it ,it has an ImportError.I use Mac.
But I can run it successfully use Pycharm
So how to run it successfully by Terminal.Because I want to run it in a Ubuntu server with cron
Thanks you for your answers.Here I show my solution.I modify my handler.py I think it may be related to The Module Search Path.
So I add the project path to the PYTHONPATH.
import os
project_home = os.path.realpath(__file__)
project_home = os.path.split(project_home)[0]
import sys
sys.path.append(os.path.split(project_home)[0])
import shutil
from modules import db, json_parse, config_out
from init_log import init as initlog
initlog()
if __name__ == '__main__':
try:
columns = json_parse.json_parse()
if not columns:
sys.exit()
is_table_has_exist = db.check_tables_exist(columns=columns)
if is_table_has_exist:
db.check_columns(columns=columns)
is_ok, config_path = config_out.output(columns)
if is_ok:
file_name = os.path.split(config_path)[1]
shutil.copy(config_path, os.path.join("/app/statics_log/config", file_name))
except Exception, e:
print e
And I run with crontab by this.
cd to/my/py_file/path && /project_path/.env/bin/python /path/to/py_file
example:
13 8 1 * * cd bulu-statics/create_config/ && /home/buka/bulu-statics/.env/bin/python /home/buka/bulu-statics/create_config/handler.py >> /app/statics_log/config/create_config.log
PyCharm automatically adds project directories marked as containing sources to the PYTHONPATH environment variable, whihc is why it works from within pycharm. On the terminal use
PYTHONPATH=${PWD}/..:${PYTHONPATH} python handler.py
You can use explicit relative imports:
from .modules import db, json_parse, config_out
The proper way to do this is to turn your project into a proper Python package by adding a setup.py file and then installing it with pip install -e .
probably because PyCharm added your project folder to the PythonPath, so you can run you app inside PyCharm.
However, when you try to run it from command line, python interpreter cannot find these libs in Python python, so what you need to do is to add your python virtualenv the python python.
there are different ways to adding python path, but I would suggest you to follow:
prepare a setup.py you'll need to specify packages and install_requires.
install your app locally in development mode via pip install -e /path/to/your-package -> it'll create a egg-link in your python virtualenv, you can run your app in your local terminal from now on;
for packing and releasing, you may want to build an artifact by following https://docs.python.org/2.7/distutils/builtdist.html
you may pip install or easy_install the artifact on your other machines. you also can release your package to PyPi if you want.