I have working Python project which use pytesseract library.
I tested it in PyCharm. Python ver. 3.7.
Now I'm trying to compile this project to exe using PyInstaller.
When I run exe I got error:
File "getTextFromScreen.py", line 5, in ModuleNotFoundError:
No module named 'pytesseract' [9188] Failed to execute script main
My import in code looks like:
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'Tesseract-OCR\tesseract'
I provide whole 'Tesseract-OCR' folder in python project folder and compiled project folder.
I don't know what do I do wrong.
I want to ask you for help
Are you using windows? You must include the .exe extension in your path. Instead just r'Tesseract-OCR\tesseract', use r'Tesseract-OCR\tesseract.exe'. I have a project using PyTesseract too, provide a whole tesseract folder in python project and working well after compiled using PyInstaller.
If you want to create an .exe and run it from any other pc where the Tesseract is not, you must use the auto-py-to-exe tool, in the additional files option attach the folder where all the Tesseract files were installed, then put this in your code
import sys
if getattr(sys, 'frozen', False):
_path = os.path.join(sys._MEIPASS, './tresseract/tesseract.exe')
print(_path)
pytesseract.pytesseract.tesseract_cmd =_path
# the .exe will look here
else:
pytesseract.pytesseract.tesseract_cmd = r"C:\tresseract\\tesseract.exe"
#ruta donde se encuentre su tresseract
and compile, good luck !!
Related
I have a python script that I compiled to an EXE, one of the purposes of it is to extract a 7z file and save it to a destination.
If I'm running it from PyCharm everything works great, this is the code:
def delete_old_version_rename_new(self):
winutils.delete(self.old_version)
print("Extracting...")
Archive(f"{self.new_version}_0.7z").extractall(f"{self.destination}")
print("Finished")
os.rename(self.new_version, self.new_name)
I used pyinstaller to compile the program and used to command pyinstaller --onefile --paths {path to site packages} main.py
Thanks!
Single-file executables self-extract to a temporary folder and run from there, so any relative paths will be relative to that folder not the location of executable you originally ran.
My solution is a code snippet such as this:
if getattr(sys, 'frozen', False):
app_path = os.path.dirname(sys.executable)
else:
app_path = os.path.dirname(os.path.abspath(__file__))
which gives you the location of the executable in the single-file executable case or the location of the script in the case of running from source.
See the PyInstaller documentation here.
Eventually i just used a 7z command line i took from https://superuser.com/questions/95902/7-zip-and-unzipping-from-command-line
and used os.system() to initialize it.
Since my program is command line based it worked even better since its providing a status on the extraction process.
Only downside is i have to move the 7z.exe to the directory of my program.
I am trying to compile my python file to executable file using pyinstaller.
I put all the dependent packages and the source python file in one folder.
And I tried pyinstaller --onefile [my python file name].py
It succeeded to build the exe file. However, the exe file fails to run and I checked the warn-[my python script name].txt, there is one invalid module from which I imported the class to my python code.
In my code, I also imported another module, it was working.
from autobench.inst import power, func_gen
from autobench.i2c.aa_i2c import AAreadWrite
invalid module named autobench.i2c.aa_i2c - imported by C:\Users\jgou\Desktop\test\AP711T_OTP_Program.py (top-level)
Autobench and inst and i2c are folders. Power, func_gen and aa_i2c are python files (.py), AAreadWrite is class in aa_i2c file.
Please suggest what is wrong and how to fix this one. Thanks.
I'm using cx_freeze to pack my Python script as a standalone executable.
The exe is running fine on the machine it was packed (with python 3.5 and all the relevant packages).
But when I copied the folder cx_freeze created to another machine the I got this error:
My cx_freeze script:
import sys
import numpy
import os.path
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name = "DocSum",
version = "1.0",
options = {"build_exe": {"packages":["idna","asyncio", "encodings","numpy", "jinja2.ext"]}},
description = "DocSumRESTfulServer",
executables = [Executable("DocSumRESTfulServer.py", base = None)]
)
Any idea what could be the reason? I thought that the exe should be a standalone (run on machines without python). Am I wrong?
It seems that not all dependencies were compiled successfully.
If you want to have a standalone executable, I recommend pyinstaller.
Just pip install it then:
pyinstaller.exe --onefile yourFile.py
The --onefile flag is used to package everything into a single executable. Your executable file would be found on the dist folder.
You could also try this site.
I had the same problem. At the end I discovered that I need to copy also my python37.dll and the lib directory.
If the exe, dll and the directory are on the same directory, it works.
I would like to have a single exe too.
Error message from running my exe:
ModuleNotFoundError: No module named 'openpyxl'
testHi.py
#simple test to see if openpyxl module works
import openpyxl
print ("hi")
input()
hook-openpyxl.py
# taken from pyinstaller dev team, store in same dir as testHi.py
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('openpyxl')
cmd line input:
pyinstaller.exe --onefile --icon=py.ico --additional-hooks-dir=. hiTest.py
I run the the hiTest and get the error above.
I have looked everywhere for this solution. Can anyone tell me what I am doing wrong.
I fixed my issue by installing it through Pip, rather than install the package through Pycharm, and Pyinstaller was able to find the package.
I got the idea from looking through the text in the command prompt and saw it was loading modules that I had installed via Pip and not through Pycharm.
I was able to get this working using auto-py-to-exe (which uses pyinstaller) by including the following folders/files from my python library into the same folder that I run pyinstaller from:
jdcal.py
openpyxl (folder)
et_xmlfile (folder)
pyinstaller command:
pyinstaller -y -F "[directory]/myscript.py"
Notes on Library Location:
Windows library location for me was: C:\users[username]\AppData\Local\Programs\Python\Python37-32\Lib
The packages were in the "site_packages" folder
use
--hiddenimport openpyxl
long with the previous solutions, it worked for me, I was able to enforce the import of openpyxl.
You was quite close. :-)
I fixed the problem by modifying the "hook-openpyxl.py" file. The command collect_data_files('openpyxl') actually returns an empty list. But there is another command collect_submodules which seems to do what we want. So my "hook-openpyxl.py" file looks like this.
from PyInstaller.utils.hooks import collect_submodules
hiddenimports = collect_submodules('openpyxl')
I placed the "hook-openpyxl.py" file in the same directory like my spec file. In the spec file I set to location of the new hook file
a = Analysis(
...
...
hookspath=['.'],
...
...
...
I guess, you will have the same result with your command line parameter
pyinstaller.exe --onefile --icon=py.ico --additional-hooks-dir=. hiTest.py
My environment
Python=3.8
openpyxl=3.0.10
PyInstaller=4.8
I have converted a python game I designed into an exe. Running the exe itself causes it to flash and then close, meaning an error has occured. Running it from the Command Prompt causes the error as well, but documents it:
Cannot load image: Playfield.png
Couldn't open images\Playfield.png
This is telling me that the load_image block is failing. I have encountered this before when I did not have an images directory.
I attempted to move the images folder to the dist directory. This is the error that shows up:
Traceback (most recent call last):
File "Table_Wars.py", line 728, in <module>
File "Table_Wars.py", line 51, in main
File "Table_Wars.py", line 236, in __init__
File "pygame\__init__.pyc", line 70, in __getattr__
NotImplementedError: font module not available
(ImportError: DLL load failed: The specified module could not be found.)
This is my first time with py2exe, so I'm not really sure what is happening. The raw python file itself, Table_Wars.py, runs as expected.
If it helps, the location for the entire Table_Wars folder is inside a folder called Games, located on my Desktop (C:\Users\Oventoaster\Desktop\Games\Table_Wars). I am running Windows 7 32 bit OS.
On request, here is the output.txt I have generated:
Folder PATH listing for volume OS
Volume serial number is 7659-4C9C
C:\USERS\OVENTOASTER\DESKTOP\GAMES\TABLE_WARS
build
bdist.win32
winexe
bundle-2.7
collect-2.7
ctypes
distutils
email
mime
encodings
logging
multiprocessing
dummy
pygame
threads
unittest
xml
parsers
temp
dist
images
Here is the setup.py I used to convert the file:
from distutils.core import setup
import py2exe
setup(console=['Table_Wars.py'])
EDIT: I have attempted to use the full py2exe example. This will create the exe, but gives the same Cannot load image error. Attempting to put the images folder in the same folder as the exe creates a Runtime Error: The application requested the runtime to terminate it in an unusual way.
The shortened form of the code Slace Diamond suggested prevents py2exe from finding Table_Wars.py:
from cmd:
running py2exe
*** searching for required modules ***
error: Table_Wars.py: No such file or directory.
setup and Table_Wars are in the same directory. If it help, I input the full path to python.exe and setup.py.
EDIT: I seem to be getting closer. I put the images directory within self.extra_datas, and now I am getting this:
Fatal Python error: (segmentation fault)
This application has requested the runtime to terminate it in an unusual way. Please contact the application's suppourt team for more information
When you build a distributable package with py2exe (and py2app for that matter), part of the package environment is to point to a local resource location for files. In your plain unpackaged version, you are referring to a relative "images/" location. For the packaged version, you need to configure your setup.py to include the resources in its own location.
Refer to this doc for very specific info about how to set the data_files option of your package: http://www.py2exe.org/index.cgi/data_files
That page has multiple examples to show both very simple paths, and also a helper function for finding the data and building the data_files list for you.
Here is an example of the simple snippet:
from distutils.core import setup
import py2exe
Mydata_files = [('images', ['c:/path/to/image/image.png'])]
setup(
console=['trypyglet.py.py']
data_files = Mydata_files
options={
"py2exe":{
"unbuffered": True,
"optimize": 2,
"excludes": ["email"]
}
}
)
This closely matches what you are trying to achieve. It is saying that the "image.png" source file should be placed into the "images" directory at the root of the resources location inside the package. This resource root will be your current directory from your python scripts, so you can continue to refer to it as a relative sub directory.
It looks like you've already fixed the image problem by moving the folder into dist. The missing font module, on the other hand, is a known problem between pygame and py2exe. Py2exe doesn't copy some necessary DLLs, so you have to override py2exe's isSystemDLL method, forcing it to include audio and font related DLLs.
If Table_Wars.py is the only module in your project, try running this script with python setup.py py2exe:
from os.path import basename
from distutils.core import setup
import py2exe
origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
if basename(pathname).lower() in ("libogg-0.dll", "sdl_ttf.dll"):
return 0
return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL
setup(windows=[{"script": "Table_Wars.py"}],
options={"py2exe": {"dist_dir": "dist"}})
You could also try the example py2exe setup file on the pygame wiki. If neither of them are working, please add the error messages to your question.
I tried running py2exe on a sample project, and it also breaks for me when I use the default pygame font. If you're using the default font, try putting a ttf file in the root of your project and also in the dist folder. You'll have to change the call to pygame.Font in your script as well:
font = pygame.font.Font("SomeFont.ttf", 28)