Let’s say a third-party module moduleXYZ.py
(that I don’t want to fork/modify) does:
import ctypes from ctypes.util import find_library find_library("gsdll64.dll")
In my code main.py
I’m importing it with
import moduleXYZ
This DLL is in C:Program Filesgsgs9.56.1bin
which is not in my global system path.
Question: how to add this directory to the path (for the duration of the script run, not permanently for the system) from inside my script main.py
such that find_library will succeed?
I tried:
import os os.environ['PATH'] += ';C:Program Filesgsgs9.56.1bin' sys.path += ['C:Program Filesgsgs9.56.1bin'] import mymoduleXYZ
but it still fails.
Note:
my script is always run with
python main.py
, and I don’t want to have to add this directory to path from a batch file or from terminal or from command-line: all this should be done inside the main.py script itself.I’ve always read Permanently adding a file path to sys.path in Python, How to add to the PYTHONPATH in Windows, so it finds my modules/packages?, and similar questions but this doesn’t apply here
I don’t want to add this directory permanently to the system PATH
a general solution to add a directory to path for the currently ran script would be interesting, if possible not specific to ctypes/DLL but to everything using path in general
Edit: os.add_dll_directory
looked promising but it doesn’t work here:
import os from ctypes.util import find_library os.add_dll_directory(r'C:Program Filesgsgs9.56.1bin') find_library(r'gsdll64.dll') # None......... find_library(r'C:Program Filesgsgs9.56.1bin') # working
Advertisement
Answer
Oops, this was a noob mistake: I forgot to escape the string which contains b
with r'...'
.
This works:
main.py
import os, sys os.environ['PATH'] += r';C:Program Filesgsgs9.56.1bin' import moduleXYZ
moduleXYZ.py
from ctypes.util import find_library print(find_library(r'gsdll64.dll'))
But a more general answer that would change the system path for the currently being-ran script, from the script itself would still be interesting.