PyQt4 and pyuic4 - python

I'm trying to compile my first .ui file using PyQt4 on a mac with osx 10.6. I'm getting a syntax error and I'm not sure what it means.
>>> import sys
>>> sys.path.append('/Users/womble/Dropbox/scratch/')
>>> from PyQt4 import QtCore, QtGui
>>> pyuic4 Urb.ui > Urb.py
File "<stdin>", line 1
pyuic4 Urb.ui > Urb.py
^
SyntaxError: invalid syntax
I tried adding
#!/usr/bin/python2.5
as my first line to the .ui file and I still get the same problem.
Thanks for any suggestions.

You're mixing Python and shell commands.
This is Python code and can be executed from an interactive Python session:
import sys
sys.path.append('/Users/womble/Dropbox/scratch/')
from PyQt4 import QtCore, QtGui
This is supposed to be run from a command prompt or terminal window. It's giving syntax errors in your Python interpreter because it's not Python:
pyuic4 Urb.ui > Urb.py

I normally use pyuic4 from the command line in the following way:
pyuic4 -xo Urb.py Urb.ui
The x flag makes sure the generated Python code includes a small amount of additional code that creates and displays the GUI when it is executes as a standalone application.
The o flag specifies the output file to write to (in the example above: Urb.py)

After spending almost 6 hours on finding the right solution, the steps on this page is by far the most accurate that worked perfectly on my mac 10.6.8
http://www.pythonsummerschool.net/index.php?url=mac_pyqt
I can now convert *.ui files to *.py files seamlessly on terminal:
Once you have pyQt configured with sip and all relevant dependencies as described on this link, you have to go to /Applications/Python 3.2/Update Shell Profile.command and run it.
Check your path variables:
env | grep PATH
Once everything is pointing to your latest Python install then you can double check by running /Applications/Python 3.2/Update Shell Profile.command
Then its as easy as
pyuic4 /Volumes/BOOTCAMP/yourfile.ui > /Volumes/BOOTCAMP/yourfile.py
Have fun!

Related

Why does my python program not run when I double click the .sh file

OS: Ubuntu
Device: Jetson Nano developer kit 2GB
I've got a python program that I want to launch by double clicking. The reason for this is because I want to control the entire device with just a touchscreen. I've written a .sh file to launch the python program however when I double click it a terminal opens and immediately closes, the same thing happens when I run the .sh file manually through the terminal.
.sh file:
#!/usr/bin/env bash
echo "Starting"
sleep 1
cd /home/velotech/workspace
python3 detect.py
The weird thing is that when I run the command python3 detect.py manually from the terminal the program runs just fine.
Things I've tried:
Made a simple hello.py program, this one works both by double clicking the .sh file and through terminal so I don't think it has to do with my .sh file
print('Enter your name:')
x = input()
print('Hello, ' + x)
Added print statements in my python program, I've found out that the program stops working after I import two jetson libraries Jetson.inference and jetson.utils.
A snippet of the code from detect.py:
#!/usr/bin/python3
import serial
from gpsZEDF9P.ublox_gps import UbloxGps
import time
import threading as thread
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QMessageBox, QLabel, QVBoxLayout, QHBoxLayout, QFrame, QSizePolicy, QComboBox
from PyQt5 import QtCore
import sys
print("this gets printed")
import jetson.utils
import jetson.inference
print("This does not")
... rest of the code
When I run this from the terminal it works but when I run it through the .sh file it closes the terminal after the first print statement. So my question is, what could this be?
You are running:
python3 detect.py
Debug by running this instead:
python3 -m site
sleep 30
Verify that the identical $PYTHONPATH / sys.path
is used in both your terminal and double-click environments.
Take care to export a new value for that env var
if you notice a mismatch,
or use conda activate myproject
or the corresponding venv command,
so the same libraries are available in both environments.
In case anyone else comes across this, after I updated the libraries Jetson Utils and Jetson Inference it threw a warning saying jetson.utils and jetson.inference were deprecated and to use jetson_utils and jetson_inference instead. After doing so I was able to run the program from a .sh file and by double clicking it

python generator missing in uic while trying to convert .ui file to .py

I'm trying to convert a .ui file into a python file using uic file.ui -o file.py and other combinations of that, but even though the generated file is a .py file, the code that's in it is c++. After some googling and researching some uic prefixes I noticed that in my uic --help menu I only have java and cpp generators, but in every tutorial ppl have python|cpp generators.
What might be the reason for that and how can that be fixed?
The generator for python has been introduced in the latest versions of Qt so it is probably not available in your 5.9.7 version of Qt, so you will have to install a more recent version, for example in my case I use version 5.15.2:
Usage: uic [options] [uifile]
Qt User Interface Compiler version 5.15.2
Options:
-h, --help Displays help on commandline options.
--help-all Displays help including Qt specific options.
-v, --version Displays version information.
-d, --dependencies Display the dependencies.
-o, --output <file> Place the output into <file>
-a, --no-autoconnection Do not generate a call to
QObject::connectSlotsByName().
-p, --no-protection Disable header protection.
-n, --no-implicit-includes Disable generation of #include-directives.
-s, --no-stringliteral Deprecated. The use of this option won't take
any effect.
--postfix <postfix> Postfix to add to all generated classnames.
--tr, --translate <function> Use <function> for i18n.
--include <include-file> Add #include <include-file> to <file>.
-g, --generator <python|cpp> Select generator.
--idbased Use id based function for i18n
--from-imports Python: generate imports relative to '.'
Arguments:
[uifile] Input file (*.ui), otherwise stdin.
so now I can convert the .ui to .py by running:
uic file.ui -o file.py -g python
To begin with, in Ubuntu I came across that the Error is written in the console: bash: qic. It is solved by installing pyside2-tools doing sudo apt-get install pyside2-tools. File conversion is performed by uic /usr/home/menu.ui > /usr/home/menu.py

failed to create executable with pyinstaller and cefpython on Linux (Invalid file descriptor to ICU data)

I have some simple cefpython code opening a url and am trying to create a stand alone executable with pyinstaller:
I copied files from https://github.com/cztomczak/cefpython/tree/master/examples/pyinstaller to a a directry named pyinstaller
I made following minor changes to pyinstaller.spec
+SECRET_CIPHER = ""
...
- ["../wxpython.py"],
+ ["../hello.py"],
...
- icon="../resources/wxpython.ico")
+ )
I can successfully compile my application on windows with python
On the same machine with python 3.5.4 64 bit and following virtualenv:
cefpython3==66.0
future==0.18.2
PyInstaller==3.2.1
pypiwin32==223
pywin32==228
I can also compile windows with python 3.6.4 64 and following virtualenv:
altgraph==0.17
cefpython3==66.0
future==0.18.2
macholib==1.14
pefile==2019.4.18
PyInstaller==3.3.1
pyinstaller-hooks-contrib==2020.9
pypiwin32==223
pywin32==228
pywin32-ctypes==0.2.0
On Linux compilation works as well, but the executable is not operational.
I get following output and error:
CEF Python 66.0
Chromium 66.0.3359.181
CEF 3.3359.1774.gd49d25f
Python 3.5.2 64bit
[1013/180954.001980:ERROR:icu_util.cc(133)] Invalid file descriptor to ICU data received.
Trace/breakpoint trap (core dumped)
version is python 3.5.2 64bit and the virtualenv is:
cefpython3==66.0
pkg-resources==0.0.0
PyInstaller==3.2.1
What could be the cause?
The code, that I try to compile is below:
import platform
import sys
from cefpython3 import cefpython as cef
def check_versions():
ver = cef.GetVersion()
print("CEF Python {ver}".format(ver=ver["version"]))
print("Chromium {ver}".format(ver=ver["chrome_version"]))
print("CEF {ver}".format(ver=ver["cef_version"]))
print("Python {ver} {arch}".format(
ver=platform.python_version(),
arch=platform.architecture()[0]))
assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this"
def main(url="https://www.stackoverflow.com"):
sys.excepthook = cef.ExceptHook
check_versions()
settings = {}
switches = {}
browser_settings = {}
cef.Initialize(settings=settings, switches=switches)
cef.CreateBrowserSync(
url=url,
window_title="CEF_HELLO: ",
settings=browser_settings,
)
cef.MessageLoop()
cef.Shutdown()
if __name__ == "__main__":
main()
Addendum: 2020-10-14:
same error on linux with other versions:
so far I tried python 3.5 and 3.7
Is there anybody who successfully created an executable?
I could be, that this just an issue with the example project and its configuration?
As alternative, a solution could be found in PyInstaller bug 5400
Here the steps:
1- download the PyInstaller helper in CEFpython named hook-cefpython3.py from:
https://github.com/cztomczak/cefpython/tree/master/examples/pyinstaller and put in the root directory of your project
2- In that file, replace the line:
from PyInstaller.compat import is_win, is_darwin, is_linux, is_py2
with:
from PyInstaller.compat import is_win, is_darwin, is_linux
is_py2 = False
3- in your PyInstaller .spec file, add the '.' to the hookspath, e.g. hookspath=['.']. I think it is also possible to add it as PyInstaller command line option.
These steps should solve the problem, until CEFPython deliver a correct version of the hook file.
This is not really the answer I would like to accept, but it is at least one solution and contains information, that might lead to a better fix, a better answer.
After debugging with strace I found out, that the executable searches many files like for example icudtl.dat, v8_context_snapshot.bin, locales/* were searched in
'dist/cefapp/cefpython3but were copied todist/cefapp/`
An ugly work around is to do following after compilation
cd dist/cefapp/cefpython3
ln -s ../* .
and the executable works.
I'm sure there is also a nicer non-brute-force solution, but for the time being I wanted to answer in case others are stuck as well
Probably this can be fixed in the spec file but would we need one spec file for linux and one for windows then?
Perhaps there's also an option to tell the excutable to search for these files one level higer?
To solve this, you need to set this in your spec file:
hookspath=[r'YOUR_ENV_SITE_PACKAGES\cefpython3\examples\pyinstaller\']
And then rebuild, you will have things in the right place.
The following steps solved the issue for me on Windows 10, Python 3.9.5 32-bit, PyInstaller 4.3, and CEFPython 66.1:
Download the hook-cefpython3.py file from here and put it into your project root directory.
Run the pyinstaller command as usual but add the --additional-hooks-dir . command line option, so the command will look like this:
pyinstaller --additional-hooks-dir . <main-file.py>
As opposed to other answers here, this anser neither requires changes of hookspath directive in pyinstaller's spec file and, as of now, nor any changes to the downloaded hook-cefpython3.py file.

Make executable a PyQt5 project

I've tried to make a PyQt5 project an executable file.
I used a PyInstaller module, and I got a half success.
pyinstaller --clean -w -F --specpath=spec -n=project_name -i="..\resource\logo.ico" src\main.py
The executable file generated by this command did not run successfully.
The error message was like this.
pyinstaller --clean -c -F --specpath=spec -n=project_name -i="..\resource\logo.ico" src\main.py
The executable file generated by this command ran successfully.
But it has a terminal even though it is a GUI project.
The difference is just -c and -w. But one can be executed and can not one.
How should I do it?
The problem was subprocess.Popen with Python v3.7.5.
I didn't set the stdin. I set only stdout, stderr.
After I set the stdin=subprocess.PIPE, it works well.
And I want to add 1 more thing.
I've imported the win32api module with Python v3.8.0. This raises issues.
So, I've added the module pywintypes, and now the issue is resolved.
Before
import win32api
After
import pywintypes
import win32api

Cannot open .exe after pyinstaller convert

Running my GUI application created in PyQt5 using any IDLE or the file.py is running perfectly, however, when I converted the .py to .exe using Pyinstaller
I get an error every time I try to run the .exe file for some reason a small command window pops with an error and immediately disappear I screenshot the error before it closes. Any Idea Thanks in advance
Error image.
I tried to execute different commands for pyinstaller but no luck.
<pyinstaller filename -F >
<pyinstaller filename -onefile >
<pyinstaller filename >
It's an app over 900 lines and I cannot upload all of that but I think according to the error first lines.
The error occurs so here are the lines of code.
The problem is within importing modules I believe.
from PyQt5.QtWidgets import QWidget
from PyQt5 import QtCore, QtGui, QtWidgets
from datetime import datetime
import time
import os, sys #importing system modules
class Ui_MyTrophiesWindow(object):
class save_txt_file(QWidget):
def GetSaveFile(self):
path = QFileDialog.getSaveFileName(self,"Save MyTrophies.txt here", "MyTrophies", "*.txt")
working_path = os.path.abspath(__file__)[0:-13]
file = open(str(working_path) + "Txtpath.dat", "w+")
for i in path:
file.write(str(i))
file.close()
It is very common that sometimes PyInstaller won't recognize all Qt5 dependencies especially QT core DLLs. A simple way is to just locate that file on your current Python path and feed it with add-data flag in PyInstaller. Also, I suggest you not to use upx with PyQt as it may corrupt some DLLs:
pyinstaller --noupx -F --add-data "<Python_path>/Lib/site-packages/PyQt5/Qt/bin/Qt5Core.dll;./PyQt5/Qt/bin" script.py
To verify the answer suppose below example:
import traceback
import os
import sys
def func():
from PyQt5.QtWidgets import QWidget
from PyQt5 import QtCore, QtGui, QtWidgets
try:
if getattr(sys, 'frozen', False):
print(sys._MEIPASS)
func()
print("Import OK!")
except Exception:
traceback.print_exc()
input()
After you run the executable you would see the path for Pyinstaller (something like C:\Users\User\AppData\Local\Temp\_MEI90202), go to this path and search for the Qt5Core.dll and check if it is there.
I had look your error and according to me, I think you need to (re)install Qt5core.dll module and to add it in the site-package/PyQt5/init.py path. You can download the dll file here:
http://www.telecharger-dll.fr/dll-Qt5Core.dll.html
Good evening
Make sure that you have all the items of that app in the correct folder. Let me put an example that happened to me days ago:
I had an app with a folder named "options" that had 3 files (2 icons for my buttons ui and a .ini file). When I created the pyinstaller version of my program I assumed that it would somehow copy those files and pack them inside the --onefile file or into the dist folder (if not --onefile command was used). Nope, it didn't.
After scratching my head for hours, I just copied the options folder from my source files and pasted it next to my --onefile file (or inside the dist folder).
After that, my app works without issues. So... make sure it has all the files it needs in the correct folders.

Categories