I make an app that can read PDF using pdfminer.
Application is OK when development.
After that, I package to .exe file using pyinstaller. But read result is not the same with it in development.
In detail, it can not read **LTText LTTextBoxHorizontal so I can not get extracted text.
Any one know about this issue, please help me.
Logs in development
Logs after I do pyinstaller
Python 3.9.1
Pyinstaller 4.2
pdfminer.six==20201018
six==1.15.0
Command: pyinstaller --onefile file.py
Related source:
for index, page in pdf_object:
# TODO: Only read last page - maybe change if PDF file change
if index == number_of_page - 1:
# read the page into a layout object
self.interpreter.process_page(page)
layout = self.device.get_result()
print("Size of this page (%d, %d)" % (layout.x1, layout.y1))
print("len = %d" % len(layout._objs))
self.parse_obj(layout._objs)
def parse_obj(self, lt_objs):
# loop over the object list
print("Go loop")
print(lt_objs)
i = 0
for obj in lt_objs:
i += 1
print("In loop %d" % i)
Pyinstaller lib owner just answered me. It fixed by adding --additional-hooks-dir.
Please see here for detail.
Maybe they will fix in pyinstaller to support pdfminer also in next release.
Related
I've recently started learning python and am still a newbie.
How can I determine if my code run from IDE or run standalone?
My code is not imported so
__name__ == "__main__" .
Someone suggested checking sys.executable name but I'm looking for a solution independent of the file name.
P.S: I create a standalone file with pyinstaller.
Here's a link to the page pyinstaller has on their site giving information about how to check the Run-Time information of your file: https://pyinstaller.org/en/stable/runtime-information.html
Basically it says to add the following code
import sys
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
print('running in a PyInstaller bundle')
else:
print('running in a normal Python process')
This should print the 'running in a PyInstaller bundle' message if it's all self contained and properly bundled, and it should print 'running in a normal Python process' if it's still running from your source code.
For the past several weeks I have been using videowriter.write() and it has been working fine. I needed to give the program to several coworkers that have random python installations so I packaged it up in pyinstaller, which I have used successfully on other projects.
Almost everything seems to be working fine when run under pyinstaller, I can read images, capture images from the camera, show them on the screen, and write out individual images. The problem is that when I use videowriter.write() somewhere down in the bowels of the code it crashes, complaining that the images have the incorrect size. This only happens when running under pyinstaller, not when running it directly from python.
Below is a portion of the code that I extracted with a generated test image. A coworker tried to run the same example, using his copy of opencv, python, and pyinstaller and his executable seems to work. I spent the last several days trying to duplicate that setup but I don't get the same results. I have completely removed python 3 (I have a copy of 2.7 that is specifically for other tests), cleared the pip cache, cleared environment variables, and made sure all the python directories were removed prior to re-installation. I have tried python back to 3.7, different versions of opencv 4.1 through current, and all behave the same way. I have also tried using a virtual environment and setting up the core python sitting in Program Files.
The current version of opencv_videoio_ffmpeg is: opencv_videoio_ffmpeg420_64.dll.
The version that my coworker used successfully is opencv_ffmpeg410_64.dll
While it doesn't seem to make much difference, the command I have been using to build the executable is:
pyinstaller videowriter_test.py --onefile
I have also tried it without the --onefile option, it works the same but its a little harder to find the executable.
The python installation has the following installed: opencv-python, opencv-contrib-python, imutils, pynput, keyboard, virtualenv, pyinstaller. These were all installed using pip.
pyinstaller stats:
129 INFO: PyInstaller: 3.6
129 INFO: Python: 3.7.7
131 INFO: Platform: Windows-10-10.0.18362-SP0
133 INFO: wrote C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\videowriter_test.spec
137 INFO: UPX is not available. 139 INFO: Extending PYTHONPATH with paths
The test code:
import traceback
import cv2
import numpy as np
import imutils
# the rest are just there to make sure pyinstaller includes the same modules
# as my regular code
import copy
import platform
import pathlib
import select
import argparse
import warnings
import datetime
import json
import time
if __name__ == '__main__':
w = 640
h = 480
currentVideoLogFilename = "test.avi"
print(os.getenv('temppath'))
try:
print("Attempting to open Video Log:", currentVideoLogFilename)
video_log_file = cv2.VideoWriter(currentVideoLogFilename,
cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (w, h),True)
print("Open Success")
except:
traceback.print_exc()
print("Test Image Shape:", w, h)
image = np.zeros((w, h, 3))
try:
video_log_file.write(image)
except:
traceback.print_exc()
print("Completed")
video_log_file.release()
print("file closed/released")
sys.exit(0)
If I run the using idle or pyCharm, I get this result:
================== RESTART: C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\videowriter_test.py ==================
None
Attempting to open Video Log: test.avi
Open Success
Test Image Shape: 640 480
Completed
file closed/released
>>>
if I run it from the virtual environment I get:
C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\dist>videowriter_test.exe
None
Attempting to open Video Log: test.avi
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): test.avi in function 'cv::icvExtractPattern'
Open Success
Test Image Shape: 640 480
Traceback (most recent call last):
File "videowriter_test.py", line 39, in <module>
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_mjpeg_encoder.cpp:476: error: (-215:Assertion failed) imgWidth == frameWidth && imgHeight == frameHeight && channels == 3 in function 'cv::mjpeg::MotionJpegWriter::write'
Completed
file closed/released
One interesting note is what I assume is the temp directory that is referenced in the first error message. I have no idea where the directory comes from and what happens to it, it is missing when I go looking for it.
Any suggestions?
I am creating one application which sorts files and merges them based filename. I needed filepaths when i drop files from file browser to my widget's listbox. For Tkinter i installed TkDnd. I followed instructions from How to Install and Use TkDnD with Python 2.7 Tkinter on OSX? and it worked for me. I am using Anaconda and i paced folders in C:\Users\Anaconda3\tcl and C:\Users\Anaconda3\Lib\site-packages. I am using Spyder and python 3.7. I made executable from below command:
pyinstaller --onefile -w PDF_Merger.py
After opening file it gives me error:
Fatal error ".py failed to execute"
I know this problem is regarding linking TkDnd.
I have tried making executable with --onedir and it still gives me error. But after copying tkdnd2.8 to dist it works.
Here is my code using TkDnd:
from TkinterDnD2 import *
widget = TkinterDnD.Tk()
filesinfileslist = Variable(widget)
FilesShow = ReorderableListbox(widget, font=('aerial',12), height = 23 , width = 45, listvariable = filesinfileslist, selectmode = EXTENDED)
FilesShow.place(x=10, y=40)
FilesShow.drop_target_register(DND_FILES)
FilesShow.dnd_bind('<<Drop>>', drop)
drop method takes only pdf files and sets it to listBox.
As of now it works in spyder but .exe file gives me error. Can anyone show me how to resolve this issue or if i made some errors in code?
I resolved this issue with adding files from tkdnd2.8 folder with --add-data attribute while generating executable with pyinstaller. I was able to create it with onefile.
This post is already a few years old but I got to it when I looked for my problem. In the end I solved it like this:
pyinstaller --onefile --add-data=C:\ProgramData\Anaconda3\tcl\tkdnd2.8\;' myfile.py
I am trying to create a .exe file using pyinstaller and execute it
it is not fetching any result from
b = TextBlob(ar)
score = b.sentiment.polarity
it returns proper value when executed on console
but return 0 when executed with .exe
def start_dmo():
print ("Importing all the required packages...")
from textblob import TextBlob
input ("press enter to continue")
print("All Necessary Packages imported")
input("press enter to continue")
ar="I cant be more happy with this"
print(ar)
b = TextBlob (ar)
score = b.sentiment.polarity
print (b.sentiment.polarity)
input("press enter to continue")
score = round (score, 2)
if score > 0.0:
senti = "Positive"
elif score < 0.0:
senti = "Negative"
else:
senti = "Neutral"
print("Score"+str(score)+"sentiment"+senti)
input("press enter to continue")
start_dmo()
this is the output when the above code is executed on console
this is the output when the above code is executed on .exe of the same code which is created using pyinstaller
Pyinstaller is not including en-sentiment.xml in the package, so the sentiment analyzer is missing a dependency and returns 0. Textblob doesn't produce an error in this case.
pyinstaller requires that you specify any data files in myscript.spec manually. However, as you've discovered, it appears that cx_Freeze honors the setup.py configuration, which specifies the data files to be included already:
package_data={
"textblob.en": ["*.txt", "*.xml"]
}
To resolve, modify the pyinstaller myscript.spec file to copy textblob/en/en-sentiment.xml, or switch to cx_Freeze as discussed.
See my post on Github as well.
Try importing textblob before of your start_dmo function so that pyinstaller is aware of it as a dependency.
from textblob import TextBlob
start_dmo():
....
Issue Solved!
Simple Solution
Changed pyinstaller to cx_Freeze
FYI cx_Freeze works perfectly fine with python 3.6
to know how to create .exe using cx_freeze follow the below link:
https://pythonprogramming.net/converting-python-scripts-exe-executables/
if u use numpy or pandas u might need to add option cz it might not import numpy to form ur exe so solve that issue follow below link:
Creating cx_Freeze exe with Numpy for Python
Good luck!
hey copy textblob from site packages to your working directory
and run below in .spec
a = Analysis(.....
datas=[( 'textblob/en/*.txt', 'textblob/en' ),
( 'textblob/en/*.xml', 'textblob/en' )],
....)
it will work
I am trying to run the following bit of code as part of a larger python program to get my mac address:
if sys.platform == 'win32':
for line in os.popen("ipconfig /all"):
if line.lstrip().startswith('Physical Address'):
maccode = line.split(':')[1].strip().replace('-', ':')
break
else:
for line in os.popen("/sbin/ifconfig"):
if line.find('Ether') > -1:
maccode = line.split()[4]
break
When I run this code in python 3.5 as part of a .py program it works fine. When I compile my program using pyinstaller into an exe and I get to the following line it fails
for line in os.popen("ipconfig /all"):
Any ideas on how I can get around this problem? I have done some reading and I think I could use "subprocess" but I have been unsuccessful in creating the alternative line. Any help would be great.