cx_Freeze : Importing modules fails - python

I would like to compile a Python3 project with cx_Freeze, but no matter what I do I can never import my own .py files.
Here's my directory structure:
projectname/
setup.py
app/
code/
__init__.py
config.py
run.py
run - editeur.py
...
image/
...
level/
...
My setup.py :
import sys, os
from cx_Freeze import setup, Executable
path = sys.path
includes = []
excludes = []
packages = ["app/code"]
includefiles = ["app/image", "app/level"]
optimize = 0
silent = True
options = {"path": path,
"includes": includes,
"excludes": excludes,
"packages": packages,
"include_files": includefiles,
"optimize": optimize,
"silent": silent
}
base = Win32GUI
cible_1 = Executable(
script="app/code/run.py",
)
cible_2 = Executable(
script="app/code/run - editeur.py",
)
setup(
name="project",
version="1.0",
description="blabla",
options={"build_exe": options},
executables=[cible_1, cible_2]
)
The cx_Freeze compilation is going well and I get my 2 executables.
But when I try to launch one, every time I get the same error:
[...]
File "app/code/run.py", line 7, in <module>
import config
ImportError: No module named 'config'
I really have to miss something stupid since I have no problem with the plug-ins.
It may also be a problem of path or something else I don't know...
Anyone know how to help me a little ? Thanks !

EDIT: I've managed to freeze a simplified example based on your directory structure with the following modification of the setup.py script:
path = sys.path + ['app/code']
packages = []
Alternatively, you could also try the following structure (modifying the import paths accordingly):
projectname/
setup.py
config.py
run.py
run - editeur.py
...
image/
...
level/
...

Related

cx_Freeze can't find local package

I'm using dash to create a standalone desktop app. I want to use cx_Freeze to create an executable for my app.
Here's the cx_setup.py file:
import sys
from setuptools import find_packages
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': [
'cx_Logging', 'idna', 'CustomModule'
],
'packages': [
'asyncio', 'flask', 'jinja2', 'dash', 'plotly'
],
'excludes': [
'tkinter'
],
'include_files': [
'database.ini'
]
}
}
base = 'console'
if sys.platform == 'win32':
base = 'Win32GUI'
executables = [
Executable('server.py',
base=base,
target_name='App.exe')
]
setup(
name='App',
packages=find_packages(),
version='0.5.0',
description='',
executables=executables,
options=options
)
Here's what the dir looks like:
project
│ venv
│
└──src
│
└───myPackage
│ cx_setup.py
│ Module1.py
│ Module2.py
Module1.py has the following import statement:
from src.myPackage import Module2Class as mc
cx_Freeze has no problem building the exe but when it tries to run it throws the error:
ModuleNotFoundError: No module named 'src.myPackage'
I've tried putting myPackage in cx_setup.py script but it says that the package doesn't exist. I also used a setup.py to install the package using pip install . to my venv.
Try to add an empty __init__.py file in the src directory.
The import statement:
from src.myPackage import Module2Class as mc
implies that the src directory is treated as a Python module, however cx_Freeze will not recognize it as a module if the __init__.py file is missing (even if some IDEs will) and thus will fail to include files from there into the frozen executable.
You can also try to explicitly add src.myPackage to the packages list of the build_exe options:
options = {
'build_exe': {
...
'packages': [
'src.myPackage', ...
],
...
}
}
but this might not work either, for the same reason.

Compiling python project with Cx-Freeze

I'm trying to make and executable from a project I'm working on, to test it on a different computer, without requiring python installed.
I want to use cx freeze to build and exe file, and this is my project tree:
- Project
- objects
blocks.py
enemy.py
item.py
player.py
__init__.py
- scripts
camera.py
chunk_manager.py
__init__.py
- textures
- items
- player
- terrain
- UI
- void
index.py
__init__.py
main.py
settings.py
setup.py
map.json
As you can probably tell, this is a game.
Anyways, what I have done is executing just cxfreeze main.py --target-dir=./ dist and it generated a build directory with a lot of stuff in it.
It generated a linux executable, but thats fine, I want to test if I can make it python-independent first, and I'll solve the .exe part later.
So, I executed the file, and nothing happened. Then I tried running from the terminal and it said that it was missing the camera.py file. I went into the generated directory and I found out that cxfreeze had not copied that file. I tried moving in in there myself, but it did not work.
I started checking for other files, and I found out that only the textures had been copied.
I thought this was just because of the one line command I used, so I am now trying to make a setup.py file (as you can see in the file tree) but I am lost in how to import my custom packages (objects, scripts, and textures) and the files in the same directory as main.py
This is how my setup.py file looks like:
import sys
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': ['camera', 'chunk_manager'], 'path': sys.path + ['scripts']
}
}
setup(
name = "Void Boats",
version = "alpha0.1",
options = options,
executables = [Executable("main.py")])
I am not sure how would I put all the packages in the 'include' section, and I can't find anything on the internet that uses more than a simple file like helloworld.py, and the samples of cxfreeze on their github only show how to import files from one directory. Do I have to move everything into one single package and put all the files in the same 'include'? Or can I have one include for each package I have? Any help would be pretty much appreciated.
Edit: I'm running on ParrotSec 4.9 (Debian based)
Use "python -m setup.py build" on cmd, that will build exe.
Example setup with extra folders:
from cx_Freeze import setup, Executable
import sys
version = "0.0.6"
build_options = {
"packages": [],
"excludes": [],
"build_exe": "X:\\builds\\",
"include_files": ["Sequence_Sample/", "icons/"],
}
base = "Win32GUI" if sys.platform == "win32" else None
executables = [Executable("MainUIController.py", base=base, targetName="pym")]
setup(
name="Python Image Macro Project",
version=version,
description="Image Based macro project.",
options={"build_exe": build_options},
executables=executables,
)
Python 3.8 and later has problem with cx_freeze 6.1 - not copying python dll.
cx_freeze 6.2 is strongly recommended if that's the case.
You'll have to clone cx_freeze and build it, then install it to use 6.2.

Creating exe from python program that uses more than one .py file

I have a mid-size program written in Python that i wanted to make avalaible on Windows. I tried using cx_Freeze for that with setup.py looking like this:
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = "C:\\Users\w1kl4s\AppData\Local\Programs\Python\Python37-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Users\w1kl4s\AppData\Local\Programs\Python\Python37-32\\tcl\\tk8.6"
executables = [Executable("main.py", base=None)]
packages = [some, packages]
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "ProgramNAme",
options = options,
version = "1.0",
executables = executables
)
However, main.py imports other python files from directory, and those files import other ones from directory as well.
Project tree looks something like that
├── main.py
└── src
├── calculatehash.py
├── calculatesizeandhash.py
└── calculatesize.py
And calculatesizeandhash.py imports calculatesize.py and calculatehash.py files.
I don't really want to create more exe files if that's possible(No idea tho)
How should i approach this?

cx_Freeze is not finding self defined modules in my project when creating exe

I have a project that runs from GUI.py and imports modules I created. Specifically it imports modules from a "Library" package that exists in the same directory as GUI.py. I want to freeze the scripts with cx_Freeze to create a windows executable, and I can create the exe, but when I try to run it, I get: "ImportError: No module named Library."
I see in the output that all the modules that I import from Library aren't imported. Here's what my setup.py looks like:
import sys, os
from cx_Freeze import setup, Executable
build_exe_options = {"packages":['Libary', 'Graphs', 'os'],
"includes":["tkinter", "csv", "subprocess", "datetime", "shutil", "random", "Library", "Graphs"],
"include_files": ['GUI','HTML','Users','Tests','E.icns', 'Graphs'],
}
base = None
exe = None
if sys.platform == "win32":
exe = Executable(
script="GUI.py",
initScript = None,
base = "Win32GUI",
targetDir = r"built",
targetName = "GUI.exe",
compress = True,
copyDependentFiles = True,
appendScriptToExe = False,
appendScriptToLibrary = False,
icon = None
)
base = "Win32GUI"
setup( name = "MrProj",
version = "2.0",
description = "My project",
options = {"build.exe": build_exe_options},
#executables = [Executable("GUI.py", base=base)]
executables = [exe]
)
I've tried everything that I could find in StackOverflow and made a lot of fixes based upon similar problems people were having. However, no matter what I do, I can't seem to get cx_freeze to import my modules in Library.
My setup.py is in the same directory as GUI.py and the Library directory.
I'm running it on a Windows 7 Laptop with cx_Freeze-4.3.3.
I have python 3.4 installed.
Any help would be a godsend, thank you very much!
If Library (funny name by the way) in packages doesn't work you could try as a workaround to put it in the includes list. For this to work you maybe have to explicitly include every single submodule like:
includes = ['Library', 'Library.submodule1', 'Library.sub2', ...]
For the include_files you have to add each file with full (relative) path. Directories don't work.
You could of course make use of os.listdir() or the glob module to append paths to your include_files like this:
from glob import glob
...
include_files = ['GUI.py','HTML','Users','E.icns', 'Graphs'],
include_files += glob('Tests/*/*')
...
In some cases something like sys.path.insert(0, '.') or even sys.path.insert(0, '..') can help.

Creating a python executable using py2exe

I tried to create executable of my File NewExistGUI2.py, where GUI is made using wxpython. The file depends upon other two files localsettings.py and Tryone.py. I referred to py2exe documentation, and created a setup.py file as:
from distutils.core import setup
import py2exe
setup(name = 'python eulexistdb module',
version = '1.0',
description = 'Python eXistdb communicator using eulexistdb module',
author = 'Sarvagya Pant',
py_modules = ['NewExistGUI2','localsettings','Tryone']
)
and compiled the program in command line using
python setup.py py2exe
But I didn't got any .exe file of the main program NewExistGUI2.py in dist folder created. What Should I do now?
I woul recommend you create a module (ExistGUI) with the following structure:
ExistGUI
\_ __init__.py
|_ localsettings.py
|_ Tryone.py
bin
\_ NewExistGUI2.py
Your init.py should have:
from . import localsettings, Tryone
__version__ = 1.0
Your setup.py should look something like:
from setuptools import setup, find_packages
import ExistGUI
import py2exe
setup(
name = 'ExistGUI',
version = ExistGUI.__version__,
console=['bin/NewExistGUI2.py'],
description = 'Python eXistdb communicator using eulexistdb module',
author = 'Sarvagya Pant',
packages= find_packages(),
scripts=['NewExistGUI2.py',],
py_modules = ['localsettings','Tryone'],
include_package_data=True,
zip_safe=False,
)
Then run python setup.py py2exe. Make sure you include any requirements for your module in setup.py. Also, remove the previously generated dist directory, just to be sure.
Hope this helps.

Categories