cx_Freeze flashes a cmd window even using Win32GUI - python

I am new to cx_Freeze.
I started using it in a big python application. That application is using PySide and uses multiprocessing. On application start and each time a thread starts I see a cmd window flashing shortly (just open and close really quick.. no time to read anything).
Now I tried with a very simple application. Like this:
import os
import sys
import multiprocessing
from PySide import QtGui
from PySide import QtCore
from PySide import QtNetwork
if __name__ == '__main__':
# multiprocessing support
multiprocessing.freeze_support()
# init application
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication(sys.argv)
QtGui.QApplication.setQuitOnLastWindowClosed(False)
# check systemtray
if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
QtGui.QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system.")
sys.exit(1) # quick kill
wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Simple')
wid.show()
sys.exit(app.exec_())
But this is still showing and flashing a window on start.
Here is the setup file I use with this:
from cx_Freeze import setup, Executable
# dependencies
build_exe_options = {
"packages": [#"os", "sys", "glob", "re", "atexit",
"PySide.QtCore", "PySide.QtGui", "PySide.QtXml", 'PySide.QtXml',
'xml', 'P4', 'MYRefs_module', 'MYUtils_module', 'logging',
'multiprocessing'],
# "include_files": mfiles, # this isn't necessary after all
"excludes": ["Tkinter", "Tkconstants", "tcl"],
"build_exe": "build",
"icon": "img/icon.ico",
"include_msvcr":True
}
executable = [
Executable("main.pyw",
base="Win32GUI",
initScript = None,
targetName="Example.exe",
targetDir="build",
copyDependentFiles=True,
)
]
setup(
name="Example",
version="0.1",
description="Example", # Using the word "test" makes the exe to invoke the UAC in win7. WTH?
author="Me",
options={"build_exe": build_exe_options},
executables=executable,
requires=['PySide', 'cx_Freeze', 'P4', 'xml']
)
May be I am doing something wrong? Is the multiprocessing support the issue? Any hint appreciated.
Btw, I am using python 2.7.3x64 and cx_Freeze 4.3.4, PySide 1.2.2 ...

solved.
And after finding the problem, the question was probably not right.
I catch a os.system('rd /s /q somefolder') call. In one of my modules loaded.
As soon as I remove that, which is not necessary right now, the console window flashes dont show again.
I used it in one single place, but the flashes appeared in several places (threads). I used as well Popen, which apparently works fine.

Related

freezing Matplotlib Widget in QT app does not work when the widget is part of submodule

I've devellopped an app using PySide2 with two modules. A first module "targetQt.py" make the general display while the second "Score.py" is dealing with data and build some graph widgets and canvas using PySide2 and matplotlib with it's QT5Agg backend. The definition of the widget is in the second module since it depends on the data.
This app works fine while launched with python, I now wan't to build it using cx_freeze. All the graphical elements built in targetQt.py (including the ones using matplolib) works fine, QTableModels defined in Score.py works fine too but the matplotlib canvas widget defined in Score.py does not show.
Here is my setup file:
import sys,matplotlib
from cx_Freeze import Executable, setup
try:
from cx_Freeze.hooks import get_qt_plugins_paths
except ImportError:
get_qt_plugins_paths = None
include_files = []
if get_qt_plugins_paths:
for plugin_name in (
"accessible",
"iconengines",
"platforminputcontexts",
"xcbglintegrations",
"egldeviceintegrations",
"wayland-decoration-client",
"wayland-graphics-integration-client",
"wayland-graphics-integration-server",
"wayland-shell-integration",
):
include_files += get_qt_plugins_paths("PySide2", plugin_name)
# base="Win32GUI" should be used only for Windows GUI app
base = "Win32GUI" if sys.platform == "win32" else None
build_exe_options = {
# exclude packages that are not really needed
"includes":["matplotlib.backends.backend_qtagg",'Score'],
"excludes": ["tkinter","PyQt5"],
"include_files": include_files+[(matplotlib.get_data_path(), "mpl-data")],
"zip_include_packages": ["PySide2"],
}
executables = [Executable("targetQt.py", base=base)]
setup(
name="DartGame",
version="0.5",
description="An app with 2 modules",
options={"build_exe": build_exe_options},
executables=executables,
)
I've tried without putting Score.py in includes, relying on cx_freeze hability to search for dependencies, the results is the same. The way to freeze PySide2 and matplotlib app is mainly inspired by cx_freeze's samples.
I'm working with python3.7 on Windows 10
Does anyone has an idea on how to make it work?
Thanks!

cx_freeze isn't allowing me to make a gui with librosa Python3

Hello noob python user here, I am trying to make an executable using cx_freeze and librosa audio library. However every time I attempt to make the executable with cx_freeze and import the librosa library, the executable does not work. Could I have some help with this?
Note: Main code is just an example script to debugg error.
Here is main code which is example code but importing librosa. I am using this code to just
debug and it outputs the same error.
import PySimpleGUI as sg
import librosa
import IPython as ipd
sg.theme('DarkAmber') # Add a little color to your windows
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [ [sg.Text('Some text on Row 1')],
[sg.Text('Enter something on Row 2'), sg.InputText()],
[sg.OK(), sg.Cancel()]]
# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Cancel'):
break
window.close()
Here is my setup file for cx_Freeze
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": [] }
# GUI applications require a different base on Windows (the default is for
# a console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "Billy_Boy",
version = "01",
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [Executable("NACD_Work.py", base=base)])
Error Image cx_Freeze:
cx_Freeze error jpeg
Error Image pyinstaller
I managed to get a functional executable with pyinstaller, but it took some doing. For whatever reason, pyinstaller just feels like completely ignoring the existence of librosa, even when specified with hidden-import, so I wrote a custom hook:
import os.path
import glob
from PyInstaller.compat import EXTENSION_SUFFIXES
from PyInstaller.utils.hooks import collect_data_files, get_module_file_attribute
datas = collect_data_files('librosa')
librosa_dir = os.path.dirname(get_module_file_attribute('librosa'))
for ext in EXTENSION_SUFFIXES:
ffimods = glob.glob(os.path.join(librosa_dir, '_lib', f'*_cffi_*{ext}*'))
dest_dir = os.path.join('librosa', '_lib')
for f in ffimods:
binaries.append((f, dest_dir))
Even with this, I still had a missing import, but that one worked as a hidden import. So overall I got the code
import PySimpleGUI as sg
import librosa
import numpy as np
import sys
def main(args):
test_data = np.zeros(10000)
test_data[::50] = 1
print(librosa.beat.tempo(test_data))
sg.theme('DarkAmber') # Add a little color to your windows
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [ [sg.Text('Some text on Row 1')],
[sg.Text('Enter something on Row 2'), sg.InputText()],
[sg.OK(), sg.Cancel()]]
# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Cancel'):
break
window.close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
to build into a functional executable with the command
pyinstaller -F --hidden-import librosa --additional-hooks-dir . --hidden-import sklearn.utils._weight_vector .\test.py

cx_freeze debugging console?

I try to build my (fine working) python 3.6 tkinter gui app to a windows excecutable. After hours of trial an error (with some name and dll issues) I got it to run. But it seems to have varoius of bugs. Some functions seem not to work and I have no console output of the produced error... is there a way to debug the exe?
this is my setup.py
import sys
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = r'C:\Users\xxx\AppData\Local\Programs\Python\Python36\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\xxx\AppData\Local\Programs\Python\Python36\tcl\tk8.6'
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
executables = [
Executable('myApp.py', base=base)
]
build_exe_options = {"packages": ["tkinter",
"PIL",
"savReaderWriter",
"numpy",
"scipy",
"os"],
"include_files": ["tcl86t.dll",
"tk86t.dll"]}
setup(name='myApp',
version='0.1',
description='some description',
options = {'build_exe': build_exe_options},
executables=executables
)
myApp.py
is too big to post it here. This is a snippet that only works 'unfreezed'. You need an spss.sav file like this to try this out.
from tkinter import *
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk, ImageDraw
from savReaderWriter import SavReader
import numpy as np
from scipy.ndimage import gaussian_filter
import os
class MyApp:
spss_file = None
def import_spss(self, *args):
filename = filedialog.askopenfilename()
if filename:
try:
with SavReader(filename, returnHeader=True, ioUtf8=True) as reader:
spss_file = reader.all()
self.spss_file = np.array(spss_file)
except Exception as ex:
messagebox.showinfo(title="Import SPSS File",
message="Warning: wrong file format chosen! \nAccepted formats: sav")
print(ex)
return
else:
return
def main():
App = MyApp()
App.import_spss()
print("everything works fine")
main()
if you want the console window to appear, after it is frozen, just remove this code from the setup script:
if sys.platform == 'win32':
base = 'Win32GUI'
what that code does is it tells cx_Freeze to have the console window not show up, after frozen. this is only required on windows, because on other OSes,it depends on whether or not it was run from a terminal. make sure though, when you have finished debugging it, to put that code back in, or the console window will show up in your app.
by the way, one of the most annoying problems I've ever had was when making a program with tkinter and cx_Freeze. the problem was that it was starting in the wrong directory and not able to find the TK Dll. If when you run this with the console, and you see something about a file not found, chances are you are not including it or it is in the wrong directory.
have a good day!

'Font not defined' in Tkinter application freezed by cx_Freeze

I have freezed a Tkinter-using GUI Python 3.4 app with cx_Freeze and when I tried to run it, I was presented the following error:
NameError: name 'font' is not defined.
When I remove all references to font from my code (i. e., if I don't set ttk Label fonts anywhere In the code), it works just fine and the exe runs nicely. I have checked the library.zip archive created by the freeze script and it does contain the font.pyc file in the tkinter directory.
This is what my setup.py file looks like:
import cx_Freeze
import sys
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [cx_Freeze.Executable("rocnikovka.py", base=base)]
cx_Freeze.setup(
name = "Number evolution",
options = {"build_exe": {"packages":["tkinter", "tkinter.font"], "includes": ["tkinter", "tkinter.font"]}},
version = "0.01",
description = "Rocnikovka",
executables = executables
)
Any help is appreciated.
UPDATE: I have also tried making an executable out of the script with py2exe but ended up with the same result. Seems like a problem with tkinter rather than with cx_Freeze.
UPDATE #2: I import tkinter and ttk in the script like this:
from tkinter import *
from tkinter import ttk
I have a few fonts defined in the script, like this one:
font_title = font.Font(family = "Exo 2", size = 20, weight = "bold")
which I then use as the font parameter of ttk.Label objects.
This all works just fine when run as a script in IDLE.
Thanks to Arden, I was able to get it to work adding an explicit font sub-module import:
from tkinter import font
Works perfectly good now.

Using ttk with Py2App

I'm trying to figure out how to use Py2App to make one of my scripts less user hostile. The script is written using Tkinter using "notebook" from ttk, and I can't figure out how to include the ttk thing! It compiles as it should but when I try to run I get a console error: _tkinter.TclError: can't find package tile.
The problem can be replicated with:
test.py
#!/usr/bin/python2.7
from Tkinter import Tk
from ttk import Notebook
if __name__ == '__main__':
gui = Tk()
gui.wm_title("Py2App testing")
gui.wm_minsize(450, 300)
main = Notebook(gui)
main.pack(fill='both', expand='yes')
gui.mainloop()
I use a simple file which looks like:
setup.py
from setuptools import setup
APP = ['test.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True,}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app',],
)
I've tried a number of combinations of 'packages': ['ttk'], 'includes': ['ttk'],, setup_requires=['py2app', 'ttk'],, but I can't get it to work so I figured maybe someone can explain how this actually works! =)
I don't know about tile either, how do I include that?

Categories