I created a file called dork.py in Python and wrote the following inside the file:
import os,time
print(os.path.basename(__file__))
time.sleep(3)
as a result it prints dork.py on the screen
In the setup.py I created for cx_Freeze, I wrote the following:
from cx_Freeze import setup, Executable
build_exe_options = {
'packages': ['os','time'],
'include_files':['/']
}
setup(
name='YourAppName',
version='1.0',
description='Your App Description',
options={'build_exe': build_exe_options},
executables=[Executable('dork.py')]
)
When I run the exe file I want it to print dork.exe but it says dork.py. I tried this with pyinstaller and pyinstaller was giving an error
How can i solve this
I expected it to print dork.exe but it says dork.py
the __file__ will point to the original python file after freezing, this is the way cx_freeze or pyinstaller "patches" these variables when it freezes the modules.
a simple way to make it return .exe when the app is frozen is outlined in the documentation
import sys
if getattr(sys, "frozen", False):
# The application is frozen
script_path = sys.executable
else:
# The application is not frozen
script_path = __file__
print(script_path)
Related
I`m trying to make an executable from my python script called ProyectoNew.py. It works with a folder called "Imagenes" and another called "ModulosExternos", and a PyQT5's .ui file like this:
Here`s the Code posted in GitHub: https://github.com/TheFlosh/ProyectoSoftware.git
I`ve tried to use Pyinstaller, Py2Exe and CXFreeze but it didn't worked. Using each one of these modules to create a .exe file I've got the same result when I tried to execute it in another PC, as shown here:
On the LEFT of the picture you can see what I get after using pyinstaller (or Py2Exe), on the right you can see what I need to show.
Here are the modules that I use in my code ("ModulosExternos" is the folder where I put some particular modules that my code needs):
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import pyttsx3
from pyttsx3.drivers import sapi5
import PyQt5
import sip
import os
from ModulosExternos import Boton_1,Boton_2,Boton_3,Boton_4,Boton_Final,Listas_Pictogramas, Frases_Completas
And here is the last part of it, to instantiate the GUI:
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
GUI = ProyectoNew()
GUI.show()
sys.exit(app.exec())
I`ve read a lot of posts on the internet that recommended creating Setup.Py file to initiate the process of creating an executable file of my project. These are some examples of what I did with two of them:
With CX_Freeze:
import sys
import os
from cx_Freeze import setup, Executable
files = ['icono.ico','/Imagenes']
target = Executable(
script = "/ProyectoNew.py",
base = 'Win32GUI',
)
#Setup
setup(
name = "Proyect2",
version = "1.6",
description = "Software",
author = "----",
options = {'build_exe': {'include_files' : files}},
executables = [target]
)
With Py2Exe:
from cx_Freeze import setup, Executable
setup(name = "Proyect2",
version="1.0",
description = "Software",
executables = [Executable("ProyectoNew.py")],)
With Pyinstaller I typed: python --nowindowed --onefile ProyectoNew.py but I constantly got the same result as shown before.
I think that when I execute Pyinstaller, the .exe file doesn`t load the modules and the images that I use. What am I missing while creating the file? What do I need to do to execute the .exe file in another PC?.
I would prefer to use pyinstaller,but using any one of these will help me.
What's is wrong with that? You get some kind of error? Please edit your question with that.
With pyinstaller and this command, you should be able easily build an executable file:
pyinstaller [FILE].py -w -F
This command generate a /dist folder with the neccesary files and .exe file to run
*-w param is for do not provide a console window for standard i/o
*-F param is for one-file bundled executable
You can check more params here
PD: Before, you need obviously install pyinstaller:
pip install pyinstaller
When I run B.exe (located in c:/my_software/FOLDER_B/B.exe) from A.exe (located in c:/my_software/FOLDER_A/A.exe), both built with cx_Freeze, B.exe (called) tries to find his modules (like IMAGE_B.png, for example) in the A.exe folder (caller), when it would need to search in the B.exe folder. I think this is happening due to some wrong code in setup.py of cx_Freeze.
I use in my script the function os.getcwd() to get the root path in each .exe
This is my setup.py, which I used to build both .exe (A and B)
import os
from cx_Freeze import setup, Executable
import sys
os.environ['TCL_LIBRARY'] = r'c:\python\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'c:\python\tcl\tk8.6'
buildOptions = dict(packages = ["tkinter","os"],
excludes = [],
include_files [r'c:\python\DLLs\tcl86t.dll',
r'c:\python\DLLs\tk86t.dll',
'A.png','icono.ico'])
executables = [Executable('A.py',
base="Console",
icon = "icono.ico")]
setup(name='A',version = '1',
description = 'program A',
options = dict(build_exe = buildOptions),
executables = executables)
See in the cx_Freeze documentation how to use data files. It provides the following code example:
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)
Please also notice that cx_Freeze version 5.1.1 (the current version) will freeze packages into a lib subdirectory of the build directory, while the main script itself will be frozen in the build directory itself. You might need to modify the above code example accordingly.
I'm using cx_freeze to pack my Python script as a standalone executable.
The exe is running fine on the machine it was packed (with python 3.5 and all the relevant packages).
But when I copied the folder cx_freeze created to another machine the I got this error:
My cx_freeze script:
import sys
import numpy
import os.path
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name = "DocSum",
version = "1.0",
options = {"build_exe": {"packages":["idna","asyncio", "encodings","numpy", "jinja2.ext"]}},
description = "DocSumRESTfulServer",
executables = [Executable("DocSumRESTfulServer.py", base = None)]
)
Any idea what could be the reason? I thought that the exe should be a standalone (run on machines without python). Am I wrong?
It seems that not all dependencies were compiled successfully.
If you want to have a standalone executable, I recommend pyinstaller.
Just pip install it then:
pyinstaller.exe --onefile yourFile.py
The --onefile flag is used to package everything into a single executable. Your executable file would be found on the dist folder.
You could also try this site.
I had the same problem. At the end I discovered that I need to copy also my python37.dll and the lib directory.
If the exe, dll and the directory are on the same directory, it works.
I would like to have a single exe too.
I'm using cx_freeze to export a Python program. The exported program was working fine until I tried to add shortcut with icon on the desktop. I've taken the codes from there and there.
When running the main.exe file from its folder in C://Program files, there is no problem, but when I run the shortcut on the desktop there is this error :
The setup.py file :
import sys
from cx_Freeze import setup,Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includefiles = ['bouton_ajouter_contact.png','bouton_contacts.png','bouton_deconnexion.png',\
'bouton_message.png','bouton_messages.png','bouton_reglages.png','fond_home.png','worldco.png']
includes = []
excludes = []
packages = ['os']
setup(
...
options = {'build_exe': {'includes':includes,'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [Executable(
'main.py', base=base,
shortcutName="Messagerie Cryptee", shortcutDir="DesktopFolder",
icon='messagerie_cryptee_ico.ico'
)]
)
All the .png files and the .ico file are in the same folder as the setup.py file, in Python34. Before adding a shortcut, this problem was not there, and I don't remember having changed anything about images.
Thanks for help
I have a flask project, everything appears to be working fine. When using py2exe to build the package, (target server is a windows server ugh), the executable can execute, but leaves me with a ImportError: No module named 'jinja2.ext'
I have the module, and the website works fine with no ImportError when not executing from the .exe
I am pretty new at packaging and delivering, and not sure whats wrong with the setup that is causing the break from .py -> .exe conversion.
Setup.py
from setuptools import setup, find_packages
import py2exe
NAME = "WorkgroupDashboard"
VERSION = "1.0"
setup(
name=NAME,
version=VERSION,
description="Provides real time ISIS connection data",
long_description="",
# Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[],
author="Test User",
author_email='',
url='',
license='Free',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'flask >= 0.10.1',
'SQLAlchemy>=0.6'
],
console=['DashboardBack.py']
)
The idea is in order to turn the server on, just execute the .exe. Server will not have python on it. I am using Python 3.4 64 bit.
Edit: build cmd = python setup.py py2exe
Figured it out it seems, Setup commands go inside the py2exe optuons=[]
Working Setup.py
__author__ = ''
import sys
from glob import glob # glob will help us search for files based on their extension or filename.
from distutils.core import setup # distutils sends the data py2exe uses to know which file compile
import py2exe
data_files = []
setup(
name='WorkgroupDashboard',
console=['DashboardBack.py'], # 'windows' means it's a GUI, 'console' It's a console program, 'service' a Windows' service, 'com_server' is for a COM server
# You can add more and py2exe will compile them separately.
options={ # This is the list of options each module has, for example py2exe, but for example, PyQt or django could also contain specific options
'py2exe': {
'packages':['jinja2'],
'dist_dir': 'dist/test', # The output folder
'compressed': True, # If you want the program to be compressed to be as small as possible
'includes':['os', 'logging', 'yaml', 'flask', 'sqlalchemy'], # All the modules you need to be included, because py2exe guesses which modules are being used by the file we want to compile, but not the imports
}
},
data_files=data_files # Finally, pass the
)
I'd convert mine to EXE and deploy is over a host. Just get "Auto Py To Exe" application. Download it locally. Open the app, insert your project location, do some setup if you want, and then click "Convert". There you go. Flask in EXE format. Plug-in anywhere that you like without the need to have Python Interpreter.