Pyinstaller with anaconda in spyder - python-3.x

So i wrote a little programm in python with use of tkinter. The repo is found here: https://github.com/Odatas/MeisterTools
I now want to create an exe so people only need to use the exe when they want to use the program. But the exe i create with pyinstaller doesnt work and throws the error:
Import Error: cannot import name 'travel' from 'main'
The cmd i opend to creat the exe is directly out of anaconda envoirment.
I cd into the folder where all the scripts are and then run it like this:
pyinstaller --onefile patrickstools2.py
I even tried to make every import an hidden import:
pyinstaller --onefile --hidden-import=init --hidden-import=main --hidden-import=checker --hidden-import=contact --hidden-import=dangers --hidden-import=droptable --hidden-import=importexcel --hidden-import=odatasfunctions --hidden-import=randomenpc --hidden-import=scrolltest --hidden-import=sonstiges --hidden-import=travel patrickstools2.py
that doesnt help either. I added the path through Anaconda to the PYTHONPATH variable...so it should be know in any way shape or form.
The complet code is in Anaconda. The Error gets thrown in the import section of the main file:
# page classes import
import os
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
# page classes import
from . import travel
from . import contact
from . import dangers
from . import sonstiges
from . import randomenpc
I allready created an exe with pyinstaller from a previous version. But i made some changes to the structure of the programm. The run.py is only there because i work with spyder and as far as i know spyder needs it because else the import doesnt work correctly.

Related

Python to EXE - PySide2 and Custom Modules

I'm trying to create an EXE from a Python project I built and I'm running into some issues. I've done this before with PyInstaller for simpler tools and cx-freeze for tools where I use custom modules but the way I used to set it up doesn't seem to be working anymore.
In this particular case I've tried:
cx-freeze==6.10
pyinstaller==4.10
py2exe==0.11.1.0
auto-py-to-exe==2.18.0
and a few others with no luck
Everything works perfectly fine through the Python 3.8 interpreter. I'm assuming it's either because of the way I'm importing PySide2 here (which I don't normally do but did for this project to see if it would speed up my programming time) or that the EXE modules can't find my custom modules. Here is a mock version of my program (names/paths changed for simplicity):
Example folder of my project ("C:\a\MyProjects\Project1"):
Example folder of the custom module I'm using. Each using various other built-in and/or 3rd party python modules. ("C:\a\path\to\external\modules"):
Example of my main file (C:\a\MyProjects\Project1\ui.py) I want to turn into an EXE:
import os
import sys
import colorsys
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
import utils # module in project ("C:\a\MyProjects\Project1\utils.py")
sys.path.append(r"C:\a\path\to\external\modules") # custom module location for MyModule
from MyModule.foo import module1 as foo_mod1
from MyModule.foo import module2 as foo_mod2
from MyModule.bar import module1 as bar_mod1
from MyModule.bar import module2 as bar_mod2
from MyModule.baz import module1 as baz_mod1
from MyModule.baz import module2 as baz_mod2
class MainDialog(QDialog):
[...code...]
[...use of "dark.stylesheet"...]
[...use of "images\image 1.png"...]
[...use of "images\image 2.png"...]
def main():
global win
try: # try to close existing instances
win.close()
except NameError:
pass
win = MainDialog()
win.show()
if __name__ == "__main__":
app = QApplication.instance()
if not app:
app = QApplication(sys.argv)
main()
sys.exit(app.exec_())
Can someone tell me the best module and method to make this into a windowed (console-less), if possible, single file application. This is one of the more complicated tools I've had to make into a desktop app so if I can figure this out I should be good for most of the other things I have to do.
Thanks in advance.
EDIT:
Example of cx-freeze setup.py file in project I tried (C:\a\MyProjects\Project1\setup.py):
from cx_Freeze import setup, Executable
import sys
setup(
name="MyProject",
version="1.0",
options={'build_exe': {
'excludes': ["Tkinter"],
'includes': ["utils", "MyModule.foo", "MyModule.bar", "MyModule.baz"],
'path': sys.path + [r"C:\a\path\to\external\modules"],
'include_files': ["images\image 1.png", "images\image 2.png"],
'packages': ["PySide2.QtWidgets", "PySide2.QtCore", "PySide2.QtGui"]}},
executables=[Executable("ui.py", base="Win32GUI")]
Example of pyinstaller cmd command I tried:
cd C:\\a\MyProjects\Project1
pyinstaller -p "C:\a\path\to\external\modules" --onefile -w ui.py
# even tried this with a custom spec file like:
# pyinstaller --onefile -w ui.spec
There is a command in PyInstaller to include hidden modules call --hidden-module (You can use multile times). So, you can just do
pyinstaller -p "C:\a\path\to\external\modules" --onefile -w --hidden-module="example module 1" -hidden-module="example module 2" ui.py
This seems to have fixed itself after I got a new workstation and installed the latest Python (3.10) and Pyinstaller (5.1) versions.
Also think having your custom Python Libraries in the PYTHONPATH and/or PATH Environment variables may be important for allowing Pyinstaller to find them.

Error with python executable : cannot import name ttk from tkinter

I have a python (3.8.3) script which works perfectly. However, when I create an executable with the following command :
pyinstaller --onefile gui.py
I get the following error : **
cannot import name ttk from tkinter
The error appears at this line :
from tkinter import ttk
I can not remove the import as "ttk" is really needed in my program.
I tried to create it with cx_freeze but I get the same error.
Do you have any solution for this problem ? Thanks.
Try one of these ways to compile your script:
pyinstaller --onefile gui.py --hidden-import=tkinter.ttk
pyinstaller --onefile gui.py --hidden-import=tkinter
If you tackle another import problem it would be better to compile using .spec file where you can specify hidden imports

Create executable with python 3.7 PyQt5 and cx_Freeze but DLL Failed to load

I developed a "not so simple" GUI with PyQt5 via Anaconda 3 (Python 3.7) and Designer.
I have 3 different .ui files that I import in my program.
When I run cx_Freeze, everything runs good, I create the .exe. Then, I copy the "platform" folder from my "Python" folder in the "Build" folder that cx_Freeze creates.
BUT, when I pass it to an other machine without anything on it (no anaconda, no python, no cx_Freeze, nothing), the app doesn't run. I get:
ImportError: DLL load failed: The specified module could not be found
It happens in the 10th line of my code which is:
from PyQt5 import QtGui, QtWidgets
The imports in my code are:
from PyQt5 import QtGui, QtWidgets
import sys
import glob
import datetime
from matplotlib.backends.qt_compat import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import design
import flex
import entry
design, flex and entry are the .ui files. They all contain this part at the end (don't know if it helps):
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
And finally, the setup file I run with cx_Freeze:
import sys
from cx_Freeze import setup, Executable
import matplotlib
import numpy
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os", "matplotlib"], "includes": ["PyQt5", "atexit"], "excludes": ["tkinter"]}
# 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 = "Flexicounts",
version = "0.1",
description = "Flexicounts pour faire tes comptes facilement",
options = {"build_exe": build_exe_options},
executables = [Executable("flexicounts.py", base=base)])
I read a lot about it, but I feel that there is no "miracle" solution...
Could you help me freeze my app and make it run on a "virgin machine" ?
You might be facing Issue #504 of the cx_Freeze repository. In that case, quoting a comment by marceloduarte there:
The workaround is to copy python3.dll to the directory where the executable was made. cx_Freeze copies python37.dll, but does not copy python3.dll. The vcruntime140.dll may also have to be copied when it no longer exists on the system.
First try to manually copy these DLLs (you find them in the directory of your python installation containing python.exe) to the directory of your executable. If that solves the problem, you can tell cx_Freeze to do it for you by using the include_files list of the build_exe_options. Modify you setup script as follows:
import os
python_dir = os.path.dirname(sys.executable) # directory of your python installation
build_exe_options = {"packages": ["os", "matplotlib"],
"includes": ["PyQt5", "atexit"],
"include_files": [os.path.join(python_dir, "python3.dll"), os.path.join(python_dir, "vcruntime140.dll")],
"excludes": ["tkinter"]}
Maybe you need to copy further DLLs, such as msvcp140.dll, or any other DLL present inside the site-packages/PyQt5 directory (including subdirectories) of your Python installation.
I faced a similar problem recently, with the following versions:
python 3.6.6 x64
cx-Freeze==6.10
PyQt5==5.15.4
PyQt5-Qt5==5.15.2
PyQt5-sip==12.9.0
PyQt5-stubs==5.15.2.0
PyQtWebEngine==5.15.5
PyQtWebEngine-Qt5==5.15.2
Symptoms :
The cx_Freeze package was successful and execution working fine on my machine, because (as I found later and explained below) I had Python 3.6 x64 installed on my machine and visibile via environement variables.
On an another machine, the package failed with the exact same error on first PyQt5 import:
ImportError: DLL load failed: The specified module could not be found
However, in my case, all the necessary dlls seemed all in the right place :
cx_Freeze seemed to have correctly put python3.dll and python36.dll next to the executable. But no other dll were copied there (no vcruntime140.dll for instance)
all the necessary python modules were in place, including PyQt5 and all its dlls
Solution that was working :
(I created a cx_Freeze issue)
Contrary to the other answer, I had to copy
python3.dll
(either from <cx_freeze_build_dir_target> or from python3.6.6 install dir ...)
(python36.dll works too but is much bigger)
into the following folders:
<cx_freeze_build_dir_target>/lib/PyQt5/
The corresponding cx_Freeze setup config for this would be to add this to the include_files list, in the following fashion.
Unfortunatly, this does not work due to cx_Freeze having an sort of exception file liste that includes python3.dll and prevents the actual copy via include_files. So, the copy should be performed manually, after full setup script execution...
# import pkgutil
from pathlib import Path
from glob import glob
import sys
# ... your stuff
#
includes_list = []
# your stuff
# ...
# pyqt5 force copy of pythonlib(s) into qt5 target dir
# may not work if you intend to zip pyqt5 ?
python_dir = Path(sys.executable).parent
python_dlls = [ Path(p) for p in glob(f"{python_dir.as_posix()}/python*.dll")]
pyqt_base_dir = Path("lib", "PyQt5")
# prepare cx_Freeze tuples (source file, target dir)
includes_list+= [ (p, pyqt_base_dir / p.name) for p in python_dlls ]
build_exe_options = {"packages" : ..., # your packages
"includes" : ..., # yours
"include_files": includes_list,
"excludes" : ... # yours
}

Can't open Pyinstaller's output file

SOLUTION:
The main issue was occurring due to ImageTk , this can be skipped by loading image using tkinter instead of PIL.ImageTk by using this command and using this object as normal you would do with PIL.ImageTk.
my_image = PhotoImage(file ="Image location here")
MAIN ISSUE:
I'm trying to pack these files into a single executable file using pyinstaller, but after compilation, the executable file doesn't run, don't know where the error is, files in the given link, and installation log in pictures
Command Used:
pyinstaller --onefile ui.py
Where ui.py is my driver script
Files:
https://github.com/RoyalEagle73/NIT-JSR-Result-Leecher/tree/master/GUI%20%2B%20Source%20v2.0/Source
Build Log( Images ):
What I've already tried
tried Cx_Freeze as an alternative but no application seems to open the output file.
here is what I'm importing overall in the whole program
from tkinter import *
from PIL import ImageTk, Image
import fb
from tkinter.ttk import Progressbar
import webbrowser
from tkinter import messagebox
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re
from bs4 import BeautifulSoup
import time
I was not able to access the github link in your question, I think it did not get pasted properly. So I am unable to access your source files.
Try one of these:
pyinstaller --onefile --noupx ui.py
or
pyinstaller --debug --onefile --noupx ui.py
The pyinstaller uses UPX. The documentation for pyinstaller states the following:
PyInstaller looks for UPX on the execution path or the path specified
with the --upx-dir option. If UPX exists, PyInstaller applies it to
the final executable, unless the --noupx option was given. UPX has
been used with PyInstaller output often, usually with no problems.
Hope this helps.

Using py2exe by just running the script, no command-line

I know there's already a question like this but the answer didn't work for me.
When I append the py2exe argument in the program, and run it, I noticed it's missing a bunch of files. Also when I run the exe, it says
File "boot_common.py", line 46 in <module>
ImportError: No module named 'ctypes'
Can anyone help me on how to fix this? Here's my code:
from distutils.core import setup
import py2exe, sys
import tkinter as tk
from tkinter import filedialog
input('Press Enter to continue and select your Python file you want to convert when the dialog shows up...')
tk.Tk().withdraw()
file_path = tk.filedialog.askopenfilename()
sys.argv.append("py2exe")
setup(console=[file_path])
Also if it helps, I'm using a 32-bit Python interpreter.

Resources