So basically i want to convert a .py script into an executable file. The only problem is is that the setup.py file has to be in the same directory as the image and sound files, while my game file is in a directory above that with the setup.py.
How do i edit the setup file so that i dont have to go around and change all the code in my game file? If needed i'll edit the game file but preferably not.
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
snd_dir = path.join(path.dirname(__file__), 'snd')
#ways i load in images:
background = pygame.image.load(path.join(img_dir,
"background.jpg")).convert()
alien_images = []
alien_list = ['alien1.png', 'alien2.png']
for img in alien_list:
alien_images.append(pygame.image.load(path.join(img_dir,
img)).convert())`
This is the setup file i have now. Apart from it being unable to find the images and sounds of course, it is error free.
import cx_Freeze
executables = [cx_Freeze.Executable("Shmup.py")]
cx_Freeze.setup(
name = "Shoot 'm up!",
options = {"build_exe": {"packages":["pygame"],
"include_files": ["alien1.png", "alien2.png",
"background.jpg", "laser1.png",
"powerUp.png", "shield.png",
"regularExplosion00.png",
"regularExplosion01.png",
"regularExplosion02.png",
"regularExplosion03.png",
"regularExplosion04.png",
"regularExplosion05.png",
"regularExplosion06.png",
"regularExplosion07.png",
"regularExplosion07.png",
"regularExplosion08.png",
"regularExplosion09.png",
"ship1.png",
"sonicExplosion00.png",
"sonicExplosion01.png",
"sonicExplosion02.png",
"sonicExplosion03.png",
"sonicExplosion04.png",
"sonicExplosion05.png",
"sonicExplosion06.png",
"sonicExplosion07.png",
"sonicExplosion08.png",
"sonicExplosion09.png",
"Expl.wav", "Expl2.wav",
"Music.ogg", "Pew.wav",
"Powerup.wav", "Rumble.ogg"]}},
executables = executables
)
You can include a relative directory in your "include_files" directive. Something like this:
include_files = [("game_assets", "assets")]
That will copy all of the files in the directory "game_assets" to a target directory "assets". You can use whatever you wish for the names, of course!
Related
I have been following a tutorial on how to make a cx_freeze setup for pygame folders. Here is what I have come up with...
import cx_Freeze
executables = [cx_Freeze.Executable("mainGame - Copy.py")]
cx_Freeze.setup(
name = "Cave",
version = "1.0",
author = "Owen Pennington",
options = {"build_exe": {"packages":["pygame"], "include_files":["floor_heart.wav"]}},
executables = executables
)
However the rest of my files are in folders. Then there are folders inside these folders. For example I have a folder (path directory) C:CaveGame\Sprites and this folder holds many other folders, C:CaveGame\Sprites\Floors, C:CaveGame\Sprites\Lava ect... Then I also have a folder C:CaveGame\Music which holds all my music files and sound effects. How can I get these all to work inside the setup???
You just need to include the upper-level directory item in your options dictionary:
setup(name='Widgets Test',
version = '1.0',
description = 'Test of Text-input Widgets',
author = "Fred Nurks",
options = { "build_exe": {"packages":["pygame"], "include_files":["assets/", "music/"] } },
executables = executables
)
The above example will include the files assets/images/blah.png and music/sounds/sproiiiing.ogg along with their correct directories. Everything under that top-level folder is pulled into the lib/.
When you go to load these files, it's necessary to work out the exact path to the files. But the normal method to do this does not work with cxFreeze. Referencing the FAQ at https://cx-freeze.readthedocs.io/en/latest/faq.html ~
if getattr(sys, 'frozen', False):
EXE_LOCATION = os.path.dirname( sys.executable ) # frozen
else:
EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # unfrozen
Obviously you need the modules sys and os.path for this.
Then when loading a file, determine the full path with os.path.join:
my_image_filename = os.path.join( EXE_LOCATION, "assets", "images", "image.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()
EDIT: If you're building under Windows, you will need to also include the Visual C runtime: https://cx-freeze.readthedocs.io/en/latest/faq.html#microsoft-visual-c-redistributable-package . Add include_msvcr to options.
options = { "build_exe": { "include_msvcr", "packages":["pygame"] #...
I'm having troubles with praw, cx_freeze, pyside and requests, before freezing everything works fine, but when i freeze this happens, something with requests goes wrong i think:
http://pastie.org/10614254
This is the project that i'm working with: https://github.com/MrCappuccino/WallDit-QT
This is my setup.py: https://gist.github.com/MrCappuccino/0f1b0571d29d47a95895
import sys
import cx_Freeze
import PySide
import praw
import requests.certs
from cx_Freeze import setup, Executable
exe = Executable(
script="WallDit_QT.py",
base="Win32GUI",
targetName="WallDit_QT.exe"
)
#includefiles = ['README.txt', 'CHANGELOG.txt', 'helpers\uncompress\unRAR.exe', , 'helpers\uncompress\unzip.exe']
#build_exe_options = {"packages": ["os"], "includefiles": ['README.txt', 'CHANGELOG.txt']}
setup(name = 'WallDit_QT',
version = '1.0',
author = 'Disco Dolan',
description ='Set your wallpaper interactively!',
executables = [exe],
options = {'build.exe': {"include_files":['cacert.pem', 'praw.ini', 'README.md']}},
requires = ['PySide', 'cx_Freeze', 'praw', 'shutil', 'requests']
)
could anybody help out?
I have tried adding cacert.pem, to no avail, at this point i have no more ideas
For some frozen applications, you have to set the the cacert (or external data in general) path inside the frozen applications.
Setup.py Section
You first need to include it in your build options and manually specify the installation directory. This is the only part that goes inside the setup.py:
# notice how I say the folder the certificate is installed
{"include_files":[(requests.certs.where(),'cacert.pem')]}
In your case, this produces the following setup file:
import requests
import sys
# more imports
setup(name = 'WallDit_QT',
version = '1.0',
author = 'Disco Dolan',
description ='Set your wallpaper interactively!',
executables = [exe],
options = {
'build.exe': {
"include_files": [
(requests.certs.where(),'cacert.pem'),
'praw.ini',
'README.md'
]
}
},
requires = ['PySide', 'cx_Freeze', 'praw', 'shutil', 'requests']
)
Application Section
You then need to get the certificate path at runtime inside the frozen application.
For PyInstaller, a path is defined at runtime to the data directory called _MEIPASS (which can be gotten from sys._MEIPASS), allowing you to access all the data required for the application. In the case of cacert.pem, the path would be determined as follows:
cacertpath = os.path.join(sys._MEIPASS, "cacert.pem")
For cx_Freeze, the path can be determined from the path of the installation and joining it with the data desired. Here, we get the path as follows:
cacertpath = os.path.join(datadir, 'cacert.pem')
You can get the data directory easily for frozen applications with the following:
datadir = os.path.dirname(sys.executable)
(Please note that this won't work with a non-frozen application, so to ensure it works for both frozen and non-frozen applications, Cx_Freeze recommends you code it as follows):
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
You then include this path all your requests module GET and POST requests as follows:
request.get(url, headers=headers, verify=cacertpath)
Example 1
An example code snippet would be as follows:
# load modules
import os
import sys
import requests
# define our path finder
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
# get our cacert path and post our GET request
cacertpath = find_data_file('cacert.pem')
r = requests.get('https://api.github.com/events', verify=cacertpath)
# print the text from the request
print(r.text)
Example 2
You can also tell requests where to find the certificate in the future by doing the following:
os.environ["REQUESTS_CA_BUNDLE"] = cacertpath
In this case, we would do the following. The advantage here is that the cacertpath does not to be explicitly defined in every module (or imported from another module) and can be defined in the environment.
import os
import sys
import requests
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
cacertpath = find_data_file('cacert.pem')
os.environ["REQUESTS_CA_BUNDLE"] = cacertpath
r = requests.get('https://api.github.com/events')
r.text
I am trying to convert my text editor into an exe to sell it, but Windows says that python.exe is not responding when I try to convert it in cmd.
My file name is arshi.py.
Below is my setup.py:
import sys
from cx_Freeze import setup, Executable
base = None
if (sys.platform == "win32"):
base = "Win32GUI"
exe = Executable(
script = "arshi.py",
icon = "icon.PNG",
targetName = "Arshi.exe",
base = base
)
setup(
name = "Arshi Editor",
version = "0.1",
description = "A lightweight text editor for Python",
author = "Henry Zhu",
options = {'build_exe': {"packages": ["pygments"]}},
executables = [exe]
)
cx_freeze doesn't accept .png files, but rather only .ico files. Converting the .png file to an .ico file worked beautifully for me.
It is the first time I'm using cx_freeze and I really need help on this, I've been looking everywhere but i can't find an answer.
I don't have any error during the compiling process, but the executable file just doesn't do anything. Could someone please explain me why?
Here is my project structure:
Application
setup.py
application.py (Tkinter app that import 2 functions from cell.py)
logo.jpg
favicon.ico
responsible.xls
modules:
cell.py (all the work is done in this file)
I don't know where to include the file cell.py in setup, for now it's in a file Modules. And i'm not sure if Tkinter should be include or exclude.
Here is the file setup.py:
import sys
from cx_Freeze import setup, Executable
executables = [
Executable("application.py")
]
buildOptions = dict(
compressed = True,
includes = ["sys","re","PIL","ttk","xlrd","xlutils","datetime","string","Tkinter"],
include_files = ["responsible.xls","favicon.ico","logo.jpg"],
excludes = []
path = sys.path + ["modules"]
)
setup(
name = "test",
version = "1.1.1.0",
description = "test",
options = dict(build_exe = buildOptions),
executables = executables
)
You add the directories you want to include with the include_files option.
So this part of your code should be like this:
buildOptions = dict(
compressed = True,
includes = ["sys","re","PIL","ttk","xlrd","xlutils","datetime","string","Tkinter"],
include_files = ["responsible.xls","favicon.ico","logo.jpg", "modules"],
excludes = []
path = sys.path + ["modules"]
)
So with py2exe you can add additional data inside the library zip file, now I was wondering, how do you access this data, do you need to read it out from the zipfile or can you just access it like any other file ? or perhaps there's another way to access it.
I personally never used the zipfile. Instead, I pass the data files my program used in the setup method and use the bundle_files option (as described at the bottom of this page). For instance, the program I create using this call
setup(name = "Urban Planning",
windows = [{'script': "main.py", "dest_base": "Urban_Planning"}],
options = opts, # Dictionary of options
zipfile = None, # Don't create zip file
data_files = Mydata_files) # Add list of data files to folder
also has a piece before it where a config file and some images for the user interface are added like this
Mydata_files = [] # List of data files to include
# Get the images from the [script root]/ui/images/ folder
for files in os.listdir(sys.path[0] + '/ui/images/'):
f1 = sys.path[0] + '/ui/images/' + files
if os.path.isfile(f1): # This will skip directories
f2 = 'ui/images', [f1]
Mydata_files.append(f2)
# Get the config file from the [script root]/Configs folder
Mydata_files.append(('Configs', [sys.path[0] + '/Configs/defaults.cfg']))
This way I can call my config file just like I would while running the script using idle or command prompt and my UI images display correctly.