PyInstaller - How do you handle environmental variables? - python

Background:
I am trying to convert a python script to an executable file that can be used on other computers. I decided to use PyInstaller. I am using Python 2.7.13/Anaconda 2.2.0 (64-bit). I have of course seen many examples and I can achieve this for basic examples. However, the script I am now working on uses environmental variables. The following block of code appears at the start of my python script:
import os
# force qt4
os.environ['ETS_TOOLKIT'] = 'qt4'
os.environ['QT_API'] = 'pyqt'
from traits.api import HasTraits, Range, Instance, Button, on_trait_change, Bool, Str, Enum, Float, Int
from traitsui.api import View, Item, Group, HGroup, spring, Handler, Action, InstanceEditor, Menu, MenuBar, message, \
Tabbed
from mayavi.core.ui.api import MayaviScene, SceneEditor, MlabSceneModel
from pyface.api import FileDialog, OK
import yaml
from mayavi import mlab
import numpy as np
from collections import namedtuple
import gdal
Problem:
Running pyinstaller --onefile filename.py on the command line produces an .exe, but it doesn't run because of the error: ImportError: No module named qt4."qt4" isn't a module, so I am assuming the problem is with the line " os.environ['ETS_TOOLKIT'] = 'qt4'".
After looking at various questions related to PyInstaller, I know how to use 'hiddenimports', but I have no idea how to handle environmental variables. Obviously something like pyinstaller --onefile --hidden-import qt4 filename.py didn't work.

You should try pyinstaller --onefile --hidden-import "os" filename.py

Related

pyinstaller "unable to find a txt file when adding a binary"

When i was converting my script to exe using pyinstaller i got an error:-
Unable to find "c:\users\praveen\appdata\local\programs\python\python36\lib\site-packages\importlib_resources\version.txt" when adding binary and data files
You can view the full error here:
https://drive.google.com/file/d/1FmV5kdb7p6TgEZwKBFDmFIszC-Qha0BD/view?usp=sharing
my script has alot of imports, they are:-
import tkinter as tk
import os
import time
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PIL import ImageGrab
import numpy as np
import cv2
import pytesseract
import webview
what does that error mean? and why am i getting it?
You need to write the command correctly, example:
pyinstaller --add-data web_folder;web_folder --add-data db.sqlite;. gui.py
Description: title_of_folder_or_file;path_to_it (if your OS Windows use ";", else ":". On windows it's 100% but on linux or mac i don't know) for folder you need after ; set path to this folder, example web_folder;web_folder
Source - Official Documentation

when i run the exe i get No module named 'PyQt5' but from the script its work

i use windows 10, python 3.7 and pyinstaller version 3.5.
I wrote some script in pycharm and when i hit run (from the pycharm IDE) its work fine.
but when I execute it by pyinstaller to exe ("pyinstaller --onefile design.py"),
I click the file inside the dist folder (design.exe) and i get this error
Traceback (most recent call last):
File "design21.py", line 10, in <module>
ModuleNotFoundError: No module named 'PyQt5'
[11116] Failed to execute script design21
my code start with:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui_with_layouts.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread,pyqtSignal
from style import *
from firebase import firebase
import xlrd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time
from PyQt5.QtWidgets import *
stop_flag = False
UPDATE:
I dont know how but i did the next step and somehow it work:
delete line 10 and 11 (that import the 'Pyqt5')
execute new exe (from cmd the commend pyinstaller --onefile design21.py)
run the new exe file from the dist folder (Of course I got errors, because I used the moudle 'Pyqt5' without importing it).
4.add again the import line (that lines that i deleted 10 and 11).
execute again new exe (from cmd the commend pyinstaller --onefile design21.py)
then when I run the new exe it work...
no idea why but its worked.
you need to install pyqt5.
just open CMD and install it.
pip install pyqt5
No module named 'PyQt5' here not PyQt5 not installed on python environment install correctly or use the right python environment.
Pycharm editor goto project setting and choose python environment with 'PyQt5'
OR pycharm bottom CMD install a pip install PyQt5
I just ran into the same problem. For me importing sip in the first line of the programm solved the issue:
from PyQt5 import sip

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.

py2exe executes file but doesn't attempt to build

My question is rather simple: if I try to build my .exe using:
python setup.py py2exe
Python just executes my main file, starting my application, however py2exe doesn't try to build it. Meaning: it does the same as if I'd do:
python setup.py
I guess something is wrong with the distutil?
Anybody already encountered this problem?
py2exe is installed (I reinstalled it, hoping it'd fix it).
My Code:
from testmain import *
from Initfile import *
import math
import py2exe
import matplotlib
import PyQt4
import numpy
from distutils.core import setup
setup(
windows=['Initfile.py'],
data_files=[("GUI", ["testmain.ui"]),*matplotlib.get_py2exe_datafiles()],
options = {
'py2exe': {
'includes' : ['math','py2exe','numpy','matplotlib','PyQt4']
}
}
)
Well the error isn't within distutil, it seems when one imports the entry point itself (in my case Initfile.py) pyexe isnt executing.
So the solution is: remove the line from Initfile import *

Windows Python 2.7 wxwidgets and 'gizmos'

Can anyone give me precise instructions on how to access the wx 'gizmos' module?
import wx.gizmos
ImportError: No module named gizmos
The code in question has this:
import wx
import string
import wx.gizmos
from wx.lib.mixins import treemixin
import Descriptor
'pip list' reports
wxPython-Phoenix (3.0.3.dev1830+0b5f910)
Do I have the right package installed? I should add that these files are present:
\python27\Lib\wxpython\wx-3.0-msw\wx\gizmos.py
\python27\Lib\wxpython\wx-3.0-msw\wx\_gizmos.pyd
[edit] For clarification, this seems to be OK so I'm reasonably sure the WX module is installed correctly.
import wx
import copy
# had to add .agw to get this to load
import wx.lib.agw.customtreectrl as CT
import DescriptorDetailsPanel
TAIA
Congrats, you have two installs of wx. You can use pkg_resources to get the one you want. Put the following at the top of the script:
__requires__ = ["wx >= 3.0"]
import pkg_resources
This will tell pkg_resources to set things up so that a version of wx of at least 3.0 will be available if you import wx rather than the default 2.x.
You can try to remove wxpython from pip install and reinstall wxpython from this site:
https://www.wxpython.org/download.php
It worked for me!

Categories