Script only works in Python installed directory - python

I have this script which read bar codes from images.
from PIL import Image
import zbar
scanner = zbar.ImageScanner()
scanner.parse_config('enable')
pil = Image.open('zbartest2.png').convert('L')
width, height = pil.size
raw = pil.tostring()
image = zbar.Image(width, height, 'Y800', raw)
scanner.scan(image)
for symbol in image:
print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
del(image)
When i put this script in python main directory which is C:\Python27 it works without any problem.
However, when i put this script outside of main directory such as C:\myscript, it gives me error saying that import zbar - module The specified module could not be found.
What is causing the problem?
I am using Python 2.7 32bits on windows Xp 32bits SP3
EDIT:
I am executing it from the IDLE window by using run module command (F5)
;full traceback
Traceback (most recent call last):
File "C:\myscript\test.py", line 2, in <module>
import zbar
ImportError: DLL load failed: The specified module could not be found.
when i type in import zbar; print zbar.__file__
i get the following msg
C:\Python27\lib\site-packages\zbar.pyd

It seems the dll is in c:\Python27 but c:\Python27 is not in the search path. Try the adding
import sys
sys.path.append("C:\Python2.7")
to your code before importing zbar.
If works correctly, then you have to configure your python's search paths in order to add C:\Python27. I work on linux, sorry I can't help you to do that on Windows.
EDIT: Well, I don't like write in an answer that I don't know how to do something. So I do some research looking for some doc that help me figure out what your problem is. And found it here importing PYD files.

Make sure you have all the files that you are importing in the same directory as this script

Related

How to fix a Ghostscript OS Error when using Pillow?

This is the error I am getting:
OS Error: Ghostscript not found on paths
When running the following function:
from PIL import Image
def convert_ps_to_png(ps_file):
img = Image.open(ps_file)
img = Image.save("file.png")# Error occurs on this line
convert_ps_to_png(ps_file_path)
Any solutions would be appreciated. The end goal is to convert a .ps file to a .png file through a script.
As per the answers to your previous questions, you need to have Ghostscript installed, and available in the system environment variable $PATH.

ImportError: DLL load failed while importing win32print

I have the following code
from win32 import win32print
for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1):
_, _, name, _ = p
print (name)
The code works.
I'm trying to create an exe file from it as follows:
cd C:\Users\xralf\AppData\Local\Programs\Python\Python38-32\Scripts
pyinstaller.exe --onefile C:\Users\xralf\Desktop\enumprinters.py
cd dist
enumprinters.exe
It writes the following error message:
ImportError: DLL load failed while importing win32print: The specified module could not be found.
How can I fix it?
There are three ways I know maybe can solve your problem:
Update your pyinstaller.
Update your pywin32.
Try to find what's the dll it needed.(In /build/name/warnname.txt).And use pyinstaller --add-binary 'the_path_of_dll:.' myscript.py
If you are using python 3.8,Please use the old version.I heard that pyinstaller worked not very well in python 3.8.

Configure pyglfw

I am trying to create an OpenGL context using Python. I am attempting to use the python bindings for GLFW but I am having trouble getting them working. I found the bindings at https://github.com/rougier/pyglfw from the GLFW main page.
I am getting the following error when I run my test program:
python HelloOpenGL.py
Traceback (most recent call last):
File "HelloOpenGL.py", line 2, in <module>
import glfw #Windowing Toolkit - GLFW
File "C:\<...>\glfw.py", line 60, in <module>
raise OSError('GLFW library not found')
OSError: GLFW library not found
I suspect that I need a glfw dll (I could be wrong). I have tried copying over the dll I use for C++ GLFW but I get the same error. I have tried both the 32 and 64 bit dlls for GLFW 3.1 compiled with the GNU compiler. I am using a Windows 10 64 bit OS and Python 3.4.
I also came across this question: Configuring glfw for Python in Eclipse. The answer is particularly unhelpful as the problem is not to do with installing pyglfw but setting up other dependencies. I did use pip to install pyglfw initially but it did not work correctly and python couldn't find the module; I have installed pyglfw manually and it is working.
Question: can someone provide instructions for setting up pyglfw? I have been unable to find anything relevant. I need to know what dependencies are needed to make it work as well.
Here is the test program:
import OpenGL.GL as gl #OpenGL
import glfw #Windowing Toolkit - GLFW
glfw.init()
if (glfw.OpenWindow(800, 600, 5, 6, 5, 0, 8, 0, glfw.FULLSCREEN) != True):
glfw.Terminate(); # calls glfwTerminate() and exits
glfw.SetWindowTitle("The GLFW Window");
I just figured this out a few seconds ago, and it turns out that on 64-bit systems with 32 bit python, you need to put the DLL in C:\Windows\SysWOW64, then python can find it.
I opened up the pyglfw module. This is a problem that will occur on Windows systems because of the way the module searches for the GLFW DLL. The module searches for the library path using ctypes.util.find_library(), which searches directories in the PATH environment variable, and not the working directory.
The solution for me was to hard-code the DLL in pyglfw. This can be done with the following code:
_glfw = ctypes.WinDLL('glfw3')
This will now load the glfw3.dll so long as it is placed in the same directory. (For older versions of GLFW the DLL is glfw.dll)
This code should replace lines 45-53 in the original code:
# First if there is an environment variable pointing to the library
if 'GLFW_LIBRARY' in os.environ:
if os.path.exists(os.environ['GLFW_LIBRARY']):
_glfw_file = os.path.realpath(os.environ['GLFW_LIBRARY'])
# Else, try to find it
if _glfw_file is None:
order = ['glfw', 'glfw3']
for check in order:
_glfw_file = ctypes.util.find_library(check)
if _glfw_file is not None:
break
# Else, we failed and exit
if _glfw_file is None:
raise OSError('GLFW library not found')
# Load it
_glfw = ctypes.CDLL(_glfw_file)
This question: find_library() in ctypes details the solutions to loading libraries on windows.
This outlines another solution, which would be to set the search path at runtime:
You can add the DLL directory to PATH dynamically at runtime (in
contrast to the Linux loader's caching of LD_LIBRARY_PATH at startup).
For example, say your DLL dependencies are in the "dlls" subdirectory
of your package. You can prepend this directory as follows:
import os
basepath = os.path.dirname(os.path.abspath(__file__))
dllspath = os.path.join(basepath, 'dlls')
os.environ['PATH'] = dllspath + os.pathsep + os.environ['PATH']

emf to jpeg conversion using PIL works in python but not pyinstaller packaged exe

I have a peculiar problem at the intersection of the EMF image format, the python PIL (as well as Pillow) image libraries, and the Pyinstaller program for packaging Python into a Windows executable.
I have a script that uses PIL/Pillow to convert an EMF file to JPEG. This works correctly when I run the python script in python. However, when I package it into an EXE using Pyinstaller.exe -F, it does not work.
With the Pillow version, I get a simple error saying
"Cannot convert image1.emf".
With the PIL version, I get a longer message that says:
Traceback (most recent call last):
File "", line 38, in
File "", line 27, in convertImageFile
File "C:\Embibe\Git\content-ingestion\src\build\convertImage\out00-PYZ.pyz\PIL
.Image", line 2126, in open
IOError: cannot identify image file 'image1.emf'
Has anyone else encountered this and found a working solution?
The gory details follow, if you need them... :-)
OS: Windows 7 64-bit (but all software is 32 bit)
Software:: Python:2.7.5, Pyinstaller:2.1, PIL:built-in with Python, Pillow: 2.4.0
Python script convImg.py:
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).convert('RGB').save(outfile)
except IOError:
print("cannot convert", infile)
run as: convImg.py image1.emf works correctly and generates image1.jpg.
When packaged to exe using \python27\scripts\pyinstaller.exe -F convImg.py and run as convImg.exe image1 gives the errors listed above for the Pillow and PIL versions.
I found a related post here, Pyinstaller troubles with Pillow but the solution for it, namely using py2app instead of pyinstaller is not an option for me since that is for MacOS and I need Windows. I considered using similar alternatives for windows, py2exe and cx_freeze, but they do not create a single self-contained exe like pyinstaller does.
Thanks,
Amit
Ok, I found the answer to my own question at http://www.py2exe.org/index.cgi/py2exeAndPIL
The issue is that PIL relies on dynamically loading many image plugins, and when packaged using pyinstaller or py2exe, it cannot find these plugins. So the key is to
a. explicitly import all the plugins in your code
b. mark the Image class status as already initialized
c. explicitly specify the target format to the save command
So, I modify convImag.py to be:
from __future__ import print_function
import os, sys
from PIL import Image
from PIL import BmpImagePlugin,GifImagePlugin,Jpeg2KImagePlugin,JpegImagePlugin,PngImagePlugin,TiffImagePlugin,WmfImagePlugin # added this line
Image._initialized=2 # added this line
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).convert('RGB').save(outfile,"JPEG") # added "JPEG"
except IOError:
print("cannot convert", infile)
After this, the pyinstaller tool works like a charm and the packaged exe runs correctly :-)
Thanks to g.d.d.c. for confirming I was on the right track with the solution!

Python weave blitz DLL error

I'm trying to use weave.blitz to speed up some code and I keep getting the following DLL error. If I run a simple code, e.g.
from scipy import * # or from NumPy import *
a = ones((512,512),'Float64')
b = ones((512,512),'Float64')
# now average
a[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] \
+ b[1:-1,2:] + b[1:-1,:-2]) / 5.
from scipy import weave
expr = "a[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]" \
"+ b[1:-1,2:] + b[1:-1,:-2]) / 5."
weave.blitz(expr)
I get the following error:
Traceback (most recent call last):
File "C:\Users\Thijs\wtest.py", line 19, in <module>
weave.blitz(expr)
File "C:\Python27\lib\site-packages\scipy\weave\blitz_tools.py", line 65, in blitz
**kw)
File "C:\Python27\lib\site-packages\scipy\weave\inline_tools.py", line 488, in compile_function
exec 'import ' + module_name
File "<string>", line 1, in <module>
ImportError: DLL load failed: Invalid access to memory location.
I'm using the latest Pythonxy and I usually write my code in Spyder; not sure if that has anything to do with it. Any ideas?
I'm also using python 2.7 64bit/weave.inline under windows 7 and just met the same issue as you described here. I searched the whole internet but this post seems like the only related one and i got no answer.
I traced the weave.inline function and try to load the pyd from compiled binary. Then i found that the loading is successful if i try
python -c "import sys; sys.path.insert(0, 'C:\\Users\\zliu\\AppData\\Local\\Temp\\zliu\\python27_compiled'); import sc_d4c0ee9cff8db6a9b5fc8352299944210;" where the module name being some hash value apparently.
However if I start python interactive then input the exact same statements in the interactive mode, it just shows
ImportError: DLL load failed: Invalid access to memory location.
So next i tried to compare the output of python -c -v "..." and python -v, finally i was able to locate the devil different line:
import string
I have no idea why python -c and python interactive are different in this or why without this module the import show such an ambiguous message. But putting it at the beginning of the script just works for me.
I am sorry for posting to such an old thread, and I do not offer an working solution or exaplantion of the problem, it is just a comment. ImportError: DLL load failed: Invalid access to memory location. I encountered the same error when trying to make my own extension of Python programmed in C. Platform Windows 32-bit.
It was a real pain because this error appeared randomly in interactive as well as in non-interactive mode in all Python environments (Spyder, Notebook, plain console...). I compiled my code using MinGW and Python's distutils (command python setup.py install). The compilation gave no warnings or errors and produced pyd file to the correct directory. But when trying to import this module import example pro my Python code it irregularly crashed (usually only one out of five attempts to import the module succeeded).
Strange was that on another computer it worked just fine... Well, I finally found a workaround - I downloaded a newer version of MinGW (before I had used the version that comes packed in Qt SDK distribution) and compiled the module again. Then it worked with no more crashes. However I did not find any systematic solution or explanation. So I might have something to do with the compiler (maybe absence of its DLLs? I do not know exactly) that was used to generate the pyd file.

Categories

Resources