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']
Related
This question already has answers here:
Can't import dll module in Python
(6 answers)
Closed 11 months ago.
I am trying to upgrade a library to Python 3.10. Up to now, I have been using 3.7.6.
In my library, I am using DLLs. In the package __init__.py, I add the DLL path to the PATH variable. Since I want to have the code compatible with 32 and 64 bit systems, I check the bitness at runtime and add the appropriate DLL folder to the PATH:
import os
import sys
# Add libs to PATH environment variable such that DLLs can be loaded.
# Load either x64 or x86 depending on whether we are running a 32/64
# bit system.
package_directory = os.path.dirname(os.path.abspath(__file__))
if sys.maxsize > 2**32:
path_dir = os.path.join(package_directory, 'libs', 'x64')
else:
path_dir = os.path.join(package_directory, 'libs', 'x86')
os.environ['PATH'] += os.pathsep + path_dir
The corrresponding folder structure is
package_root
|- libs
|- x64
|- libbristolpolled.dll
...
|- x86
|- libbristolpolled.dll
...
Then in a sub-package, I am using:
from ctypes import CDLL
dll = "libbristolpolled.dll"
_lib_bristlp = CDLL(dll)
This has worked fine in 3.7.6 but fails in 3.10.3 with the following error message:
File "C:\...\lib\site-packages\optoMD\sensor\optical\bristol\dll_api.py", line 37, in <module>
_lib_bristlp = CDLL(dll) # The correct DLL
File "C:\Program Files\Python310\lib\ctypes\__init__.py", line 374, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'libbristolpolled.dll' (or one of its dependencies). Try using the full path with constructor syntax.
If I instead use the absolute path, as the error message suggests, it works:
from ctypes import CDLL
dll = r"C:\...\libs\x64\libbristolpolled.dll"
_lib_bristlp = CDLL(dll)
What is the reason the old method doesn't work anymore, or how can I make it work again? I'd prefer not to have absolute paths in my code and I liked the fact that I handle the DLL path once in the init file and afterwards I just need to import the DLL using the file name.
This particular features (by adding the path to find a .dll to PATH environment variable) has been removed in Python 3.8. As per the notice, the new function os.add_dll_directory is provided; quoting the documentation for the reason for the change:
New in version 3.8: Previous versions of CPython would resolve DLLs using the default behavior for the current process. This led to inconsistencies, such as only sometimes searching PATH or the current working directory, and OS functions such as AddDllDirectory having no effect.
The more portable solution going forward is to attempt to use that function, alternatively just generate the absolute path as you have current done using os.path.dirname and os.path.join on the dll variable - i.e. to maintain compatibility with prior Python versions; also this assumes those .dll files do not have external dependencies, if there are, this thread has a significantly more detail regarding the issues at hand (even with absolute paths - though given that it did appear to work for your program and library, this should not an issue for your use case).
I'm a beginner to python. I have installed python on my laptop and its version is Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:19:08) [MSC v.1500 32 bit (Intel)] on win32. I'm trying to import an existing framework created by others and creating a new sample python file using the existing package. I wrote a simple line:
from machine_lib.pydblib import db
The pydblib is a file automatically generated from SWIG. The below code is grabbed from the SWIG file:
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
pkg = __name__.rpartition('.')[0]
mname = '.'.join((pkg, '_pydblib')).lstrip('.')
try:
return importlib.import_module(mname)
except ImportError:
return importlib.import_module('_pydblib')
_pydblib = swig_import_helper()
The error is at the except block : return importlib.import_module('_pydblib') which says :
ImportError: DLL load failed: The specified module could not be found in pycharm.
I have gone through the answers for the same error and nothing worked. How can I get rid of this error? I'm happy to share more info if required. Thanks in advance!
Related note if you came here searching for "python", "import error" and "DLL load failed": in Python 3.8 DLL resolution under Windows has changed. Also see what's new in Python 3.8:
DLL dependencies for extension modules and DLLs loaded with ctypes on Windows are now resolved more securely. Only the system paths, the directory containing the DLL or PYD file, and directories added with add_dll_directory() are searched for load-time dependencies. Specifically, PATH and the current working directory are no longer used, and modifications to these will no longer have any effect on normal DLL resolution. If your application relies on these mechanisms, you should check for add_dll_directory() and if it exists, use it to add your DLLs directory while loading your library. Note that Windows 7 users will need to ensure that Windows Update KB2533623 has been installed (this is also verified by the installer).
You can also use ProcessMonitor to check the name of DLLs Python is looking for.
I would like to get started with using libclang with Python. I am trying to get a sample code (http://www.altdevblogaday.com/2014/03/05/implementing-a-code-generator-with-libclang/) to work on Windows, here is a part of the code I'm trying to run:
#!/usr/bin/python
# vim: set fileencoding=utf-8
import sys
import os
import clang.cindex
import itertools
...
print("Setting clang path")
# I tried multiple variations. Libclang is correctly installed in the specified location.
#clang.cindex.Config.set_library_path('C:/Program Files (x86)/LLVM/bin')
#clang.cindex.Config.set_library_path('C:/Program Files (x86)/LLVM/bin/libclang.dll')
# I also tried moving the dll into the Python installation folder.
clang.cindex.Config.set_library_file('C:/Python27/DLLs/libclang.dll')
print("Clang path set")
index = clang.cindex.Index.create()
...
I stripped all the other parts of the code, but I can post them if they are relevant. The line
index = clang.cindex.Index.create()
Throws the following error:
Setting clang path
Clang path set
Traceback (most recent call last):
File "D:\libclangtest\boost_python_gen.py", line 60, in <module>
index = clang.cindex.Index.create()
File "D:\libclangtest\clang\cindex.py", line 2095, in create
return Index(conf.lib.clang_createIndex(excludeDecls, 0))
File "D:\libclangtest\clang\cindex.py", line 141, in __get__
value = self.wrapped(instance)
File "D:\libclangtest\clang\cindex.py", line 3392, in lib
lib = self.get_cindex_library()
File "D:\libclangtest\clang\cindex.py", line 3423, in get_cindex_library
raise LibclangError(msg)
clang.cindex.LibclangError: [Error 193] %1 is not a valid Win32 application. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().
What is the reason for this? Am I setting the dll's path wrong? I tried multiple ways, with foreslashes and backslashes, I also tried to move the dll out of Program Files to make the path contain no spaces, but nothing worked.
I am a total beginner to libclang and Python, sry if I'm asking something trivial.
I was running into a similar problem (Windows 7 x64, Anaconda3 x64). Using
import clang.cindex
clang.cindex.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
fixed the problem. Please note that you need to use slashes (not antislashes), and specify path to bin/libclang.dll (not to lib/libclang.dll).
#SK-logic commented that I should check whether both Python and libclang are either 32bit or 64bit. Libclang was 32bit, but I couldn't find a way to check whether my Python installation is 32 or 64, so I reinstalled the 32bit version, and now it works. So the problem probably was that I had the 64 bit version of Python.
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.
I am trying to use py2exe to distribute a python application I have written. Everything seems to go OK, but when I run it on another machine it fails with the following error:
Traceback (most recent call last):
File "application.py", line 12, in <module>
File "win32api.pyc", line 12, in <module>
File "win32api.pyc", line 10, in __load
ImportError: DLL load failed: The specified procedure could not be found.
I have googled for this and not found very much, but have tried the following suggestions to no avail:
Imported pywintypes and pythoncom before win32api (in the setup.py for py2exe and in the main application)
Added some code to the setup.py -
# ModuleFinder can't handle runtime changes to __path__, but win32com uses them
import pywintypes
import pythoncom
import win32api
try:
# if this doesn't work, try import modulefinder
import py2exe.mf as modulefinder
import win32com
for p in win32com.__path__[1:]:
modulefinder.AddPackagePath("win32com", p)
for extra in ["win32com.shell"]: #,"win32com.mapi"
__import__(extra)
m = sys.modules[extra]
for p in m.__path__[1:]:
modulefinder.AddPackagePath(extra, p)
except ImportError:
# no build path setup, no worries.
pass
I'm quite new to all this, so any help would be greatly appreciated
Thanks
Jon
I've seen this problem when the package was built on Vista but executed on XP. The problem turned out to be that py2exe mistakenly added powrprof.dll and mswsock.dll to the package. Windows XP contains its own copies of these files though, and can't load the Vista ones which got installed with your app.
Removing them from the package did the trick, you can do this easy by adding this to the options dict in setup.py
'dll_excludes': [ "mswsock.dll", "powrprof.dll" ]
#Wim, I found the bit about "adding this to the options dict in setup.py" a bit confusing. If like me you did not have an options arg in your existing call to setup this might make things clearer:
setup(name='myprog',
...
options={"py2exe":{"dll_excludes":[ "mswsock.dll", "powrprof.dll" ]}},
...
)
Try adding win32api to your packages, in the options dictionary.
Here's an example:
excludes = ["pywin", "pywin.debugger"] # there will be more in real life...
options = dict(optimize=2,
dist_dir="build",
excludes=excludes,
packages=["win32api"])
setup(
name="MyCoolApp",
options=dict(py2exe=options),
# etc ...
Just as an added comment. When rebuilding your program with Py2exe be sure to delete the old "dist" directory. I was sitting for over 3 hours not understanding why my app was working on my dev envirnoment and not in production. deleted dist and rebuild with py2exe and it worked.