Python 3 + pyQt5 + cx_freeze - python

Past day has basically been a continuous frustration. I'm trying to create my first pyQt5 application and freeze it to OSX app. Here short chronology of my efforts so far:
Noticed that PyQt5 install is only for Python3. Installed Python3 and pyQt via Homebrew.
Developed application. Everything works when launched from PyCharm.
Installed cx_freeze from source to Python3 since Pycharm's pip installer failed in task.
Trying to freeze the application with cx_freeze only to get syntax error. Resolved it with following advice applied to pyQt5: SyntaxError when using cx_freeze on PyQt app
Checked tutorial for cx_freeze: http://www.pythonschool.net/cxfreeze_mac/ and created a setup.py by the example:
application_title = "simple_PyQt4" #what you want to application to be called
main_python_file = "main.py" #the name of the python file you use to run the program
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includes = ["atexit","re"]
setup(
name = application_title,
version = "0.1",
description = "Sample cx_Freeze PyQt4 script",
options = {"build_exe" : {"includes" : includes }},
executables = [Executable(main_python_file, base = base)])
Run the cx_freeze with "bdist_mac" parameter. This time .app file was generated. However, it doesn't launch. Can't see any errors or information anywhere. Just doesn't launch at all when clicked.
At this point I'm getting really tired of all of this so please help. If you can, please help me either:
1. Install PyQt5 to Python2.7 with Homebrew (tried, couldn't figure it out) so that I can use packaking tools compatible with Python2.
2. Get the freezing process to work properly. If possible give detailed explanations, I'm new to these tools.
I'm also interested in hearing how people are supposed to deploy standalone applications with pyQt5 since the process seems anything other than straightforward.
EDIT: I ran the result "main" in folder as suggested by ThomasK. I got following error but have no idea what it means:
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/cx_Freeze-4.3.2-py3.3-macosx-10.9-x86_64.egg/cx_Freeze/initscripts/Console3.py", line 27, in <module>
exec(code, m.__dict__)
File "main.py", line 8, in <module>
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1565, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1512, in _find_and_load_unlocked
_call_with_frames_removed(import_, parent)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 313, in _call_with_frames_removed
return f(*args, **kwds)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1565, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1529, in _find_and_load_unlocked
raise exc
ImportError: No module named 'ui'
On main.py I have this import on line 8:
from ui.main import Ui_MainWindow
I have all the .ui files and their .py counterparts at folder named "ui" in my project directory.
EDIT: Output of the freezing process: http://pastebin.com/RR9pNGfR
EDIT: And my project schema: http://pastebin.com/HmsdNXEb

I don't know how far the original poster ever got in solving their problem, and the pastebins referenced are long since deleted so there's not a lot of supplementary material, but the latest version of those cx_freeze instructions at pythonschool, updated on 2014-08-27 (after this question), says:
Unfortunately the current version of cx_Freeze on Mac OS X does not play particularly nicely with Python versions that have been installed from Python.org or PyQt if you have installed it previously using our instructions. Therefore, to ensure that cx_Freeze installs successfully you will need to install Python and PyQt using a package manager called MacPorts.
So, that may have been the problem all along. Installing Python3 and PyQt "via Homebrew" sounds like it may have also resulted in a problematic configuration.

Related

Why do I get Type Error when trying to plot with matplotlib? [duplicate]

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.
Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

Importing matplotlib causes "int() argument must be a string" error

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.
Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

Python app created via Pyinstaller does not run

I made a simple, one-file script that I would like to share with the end-user. I found that Pyinstaller does the job so I refactor my project structure regarding.
I have a project dir. Inside that, I have the package that has an empty __init__.py and a __main__.py with the actual script with a few include to libraries like opencv-python, numpy, etc. Outside of the project, I have a setup.py and an entry-point script that imports the main function from the __main__.py and calls it.
Then I have created the executable against this entry-point with PyInstaller in --onefile mode. When I use the created executable on my machine it does the job perfectly but when I send it to the end-user it ends up with an error (see below). I am not quite sure whats this error means but I saw paths in that to my dev environment which should be not there on other machines. It looks like it missing the dependencies but I thought that PyInstaller bundles these dependencies into the executable.
What am I missing here? I have read many regarding questions here in StackOverflow but I couldn't find a solution.
I developed this script using PyCharm on the latest macOS within a venv created by PyCharm. The venv folder is in the project dir - I don't know that could be a problem.
Traceback (most recent call last):
  File "PyInstaller/loader/rthooks/pyi_rth_pkgres.py", line 11, in <module>
  File "/Users/hordon/Documents/DEV/projects/scan_detect/venv/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 627, in exec_module
  File "setuptools-40.8.0-py3.7.egg/pkg_resources/__init__.py", line 33, in <module>
  File "/Users/hordon/Documents/DEV/projects/scan_detect/venv/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 627, in exec_module
  File "platform.py", line 116, in <module>
  File "/Users/hordon/Documents/DEV/projects/scan_detect/venv/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 627, in exec_module
  File "subprocess.py", line 153, in <module>
ImportError: dlopen(/var/folders/wk/cwx1b16j50z5_yt1ynq82hr00000gn/T/_MEI7eUUkV/select.cpython-37m-darwin.so, 2): Symbol not found: ____chkstk_darwin
  Referenced from: /var/folders/wk/cwx1b16j50z5_yt1ynq82hr00000gn/T/_MEI7eUUkV/select.cpython-37m-darwin.so (which was built for Mac OS X 10.15)
  Expected in: /usr/lib/libSystem.B.dylib
in /var/folders/wk/cwx1b16j50z5_yt1ynq82hr00000gn/T/_MEI7eUUkV/select.cpython-37m-darwin.so
[15314] Failed to execute script pyi_rth_pkgres
i have the same problem ,and sadly it's a problem of mac os. So, if you want to support different version of mac os, you need to build your app on the oldest version of mac os.
"In Mac OS X, components from one version of the OS are usually compatible with later versions, but they may not work with earlier versions.
The only way to be certain your app supports an older version of Mac OS X is to run PyInstaller in the oldest version of the OS you need to support."
https://pyinstaller.readthedocs.io/en/stable/usage.html#making-mac-os-x-apps-forward-compatible

Packaging a python application ( with enthought, matplotlib, wxpython) into executable

My Python 2.7 application uses matplotlib, enthought (mayavi, traits), wxpython libraries. I need to package it into an executable on Windows, which, after some research and experimenting seems like a not straightforward task.
I have so far experimented with PyInstaller and bbfreeze. In both of them I specify hidden imports/includes (which I could gather fromrandom information on the web) to import the Enthought packeges. Both manage to create an executable (for bbfreeze I excluded the matplotlib part of my application so far), but when I run it, both return the same error:
Traceback (most recent call last):
File "<string>", line 6, in <module>
File "__main__.py", line 128, in <module>
File "__main__test__.py", line 23, in <module>
File "traitsui/api.py", line 36, in <module>
File "traitsui/editors/__init__.py", line 23, in <module>
File "traitsui/editors/api.py", line 49, in <module>
File "traitsui/editors/table_editor.py", line 37, in <module>
File "traitsui/table_filter.py", line 35, in <module>
File "traitsui/menu.py", line 128, in <module>
File "pyface/toolkit.py", line 98, in __init__
NotImplementedError: the wx pyface backend doesn't implement MenuManager
Any ideas what should I do? Alternatively has anyone had experience with creating such an executable and can recommend a tool or method ? So far I have seen only this tutorial but it uses py2exe and apparently requires downloading the whole ETS - if nothing else gonna give it a try...
Here is the solution which worked for me.
I have tried to use bbfreeze, PyInstaller , py2exe and cx_Freeze. In the end I decided to go with cx_Freeze as it is apparently popular with people who are packaging the applications with enthought classes.
With cx_Freeze I got the similar error message as above. The problem is that it saves the necessary modules in "library.zip" file, which is something that enthought classes including mayavi have problem with. Fortunately cx_Freeze allows specifying "create_shared_zip": False option, which then makes it so that source files are directly copied into the build directory as they are, instead of in a zip file.
Additionally, I have found that some Enthought files and folders have to be manually included in include_files (same goes for scipy, source: here). After this it worked. I add my setup file code below, hope it helps.
import sys
import os
from cx_Freeze import setup, Executable
import scipy
scipy_path = os.path.dirname(scipy.__file__) #use this if you are also using scipy in your application
build_exe_options = {"packages": ["pyface.ui.wx", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_tkagg"],
"excludes": ['numarray', 'IPython'],
"include_files": [("C:\\Python27\\Lib\\site-packages\\tvtk\\pyface\\images\\", "tvtk\\pyface\\images"),
("C:\\Python27\\Lib\\site-packages\\pyface\\images\\", "pyface\\images"),
("C:\\Python27\\Lib\\site-packages\\tvtk\\plugins\\scene\\preferences.ini", "tvtk\\plugins\\scene\\preferences.ini"),
("C:\\Python27\\Lib\\site-packages\\tvtk\\tvtk_classes.zip", "tvtk\\tvtk_classes.zip"),
("C:\\Python27\\Lib\\site-packages\\mayavi\\core\\lut\\pylab_luts.pkl","mayavi\\core\\lut\\pylab_luts.pkl"),
("C:\\Python27\\Lib\\site-packages\\mayavi\\preferences\\preferences.ini","mayavi\\preferences\\preferences.ini"),
("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libifcoremd.dll","numpy\\core\\libifcoremd.dll"),
("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libmmd.dll","numpy\\core\\libmmd.dll"),
(str(scipy_path), "scipy") #for scipy
]
,"create_shared_zip": False #to avoid creating library.zip
}
executables = [
Executable('myfile.py', targetName="myfile.exe", base=None)
]
setup(name='myfile',
version='1.0',
description='myfile',
options = {"build_exe": build_exe_options},
executables=executables
)
Configuration:
python 2.7
altgraph==0.9
apptools==4.3.0
bbfreeze==1.1.3
bbfreeze-loader==1.1.0
configobj==5.0.6
cx-Freeze==4.3.3
Cython==0.23.4
matplotlib==1.4.3
mayavi==4.4.3
MySQL-python==1.2.5
natgrid==0.2.1
numpy==1.10.0b1
opencv-python==2.4.12
pandas==0.16.2
pefile==1.2.10.post114
Pillow==3.1.1
plyfile==0.4
psutil==4.1.0
pyface==5.0.0
Pygments==2.0.2
pygobject==2.28.6
pygtk==2.22.0
PyInstaller==3.1
pyparsing==2.0.3
pypiwin32==219
PySide==1.2.2
python-dateutil==2.4.2
pytz==2015.4
scipy==0.16.0
six==1.9.0
subprocess32==3.2.7
traits==4.5.0
traitsui==5.0.0
transforms3d==0.2.1
VTK==6.2.0

How to create .exe using py2exe(or pyinstaller) on Ubuntu

Given:
- Ubuntu
- py2exe and pyinstaller
- Python script with setup.py (or else)
from distutils.core import setup
import py2exe
import os
setup(
version = "1.0",
description = 'foo',
url = "",
name = "foo",
console=[{
"script":"main.py",
"dest_base":"foo",
}],
zipfile = "shared.dll",
options = {"py2exe":{
'bundle_files': 1,
'optimize': 2,
"dll_excludes": ['MSVCP90.dll', 'msvcr71.dll', "IPHLPAPI.DLL", "NSI.dll", "WINNSI.DLL", "WTSAPI32.dll"],
"includes": ["utils"]
}}
)
Need:
- One .exe file and maybe some .dll (I realy don't know)
Steps what I did:
- setup pip3 and python 3.4 (https://askubuntu.com/questions/524399/issues-with-py2exe)
- setup py2exe for ubuntu "pip3 install py2exe"
- run "python3.4 setup.py py2exe" And got following traceback:
Traceback (most recent call last):
File "setup.py", line 2, in <module>
import py2exe
File "/usr/local/lib/python3.4/dist-packages/py2exe/__init__.py", line 9, in <module>
patch_distutils()
File "/usr/local/lib/python3.4/dist-packages/py2exe/patch_distutils.py", line 68, in patch_distutils
from . import distutils_buildexe
File "/usr/local/lib/python3.4/dist-packages/py2exe/distutils_buildexe.py", line 91, in <module>
from . import runtime
File "/usr/local/lib/python3.4/dist-packages/py2exe/runtime.py", line 3, in <module>
from .dllfinder import Scanner, pydll
File "/usr/local/lib/python3.4/dist-packages/py2exe/dllfinder.py", line 5, in <module>
from . import _wapi
File "/usr/local/lib/python3.4/dist-packages/py2exe/_wapi.py", line 4, in <module>
_kernel32 = WinDLL("kernel32")
NameError: name 'WinDLL' is not defined
- setup pyinstaller for ubuntu (https://github.com/pyinstaller/pyinstaller/wiki)
- run "pyinstaller setup.py"(same as "pyinstaller -w setup.py") and got in dist folder many files with extension .so and one file "setup" without extension
What am I doing wrong?
How can I get .exe file under Ubuntu?
Is it possible?
PS: I've read Python executables: py2exe or PyInstaller? by I didn't find answer.
You cannot use py2exe on Ubuntu or Linux in general. You cannot use it on Mac either. It is a Windows-only utility! You have to use it within Windows, whether that be in a Windows virtual machine or an actual Windows machine.
As for PyInstaller, please read the docs:
Can I use PyInstaller as a cross-compiler?
Can I package Windows binaries while running under Linux?
No, this is not supported. Please use Wine for this, PyInstaller runs fine in Wine. You may also want to have a look at this thread in the mailinglist. In version 1.4 we had build in some support for this, but it showed to work only half. It would require some Windows system on another partition and would only work for pure Python programs. As soon as you want a decent GUI (gtk, qt, wx), you would need to install Windows libraries anyhow. So it's much easier to just use Wine. - source

Categories