Description
I add LD_LIBRARY_PATH to the python code like:
test.py
import os
from ctypes import CDLL
os.environ['LD_LIBRARY_PATH'] = "/home/test/myfolder/pyfolder/ztools1226/lib"
print(os.environ)
s_dll_path = f"/home/test/myfolder/pyfolder/ztools1226/lib/libCityPlanParse.so"
dll_load = CDLL(s_dll_path)
I print the os.environ the LD_LIBRARY_PATH value already exists,but when I CDLL /home/test/myfolder/pyfolder/ztools1226/lib/libCityPlanParse.so report an error:
OSError: libCityPlanParse.so: cannot open shared object file: No such file or directory
But when I join in the command-line "export LD_LIBRARY_PATH=/home/test/myfolder/pyfolder/ztools1226/lib" before executing test.py,program execution ok.
So the environment variable I added in the code is not take effect.But I need to do that.How can I write about it to take effect?
My environment
python 3.8.3
Linux system
Activity
avinash-218 commentedon Dec 19, 2024
is there any solution for this issue
duaneg commentedon May 22, 2025
Changes to
LD_LIBRARY_PATH
will not be effective after the program has started, asdlopen
is implemented by the dynamic linker that loads the program, and it reads that environment variable at initial load time. It will not notice subsequent changes (although changes will affect any child processes that inherit the parent's environment).This is nothing to do with python per se, it is just how Linux (and I assume other POSIX systems) work. The same applies if you use
putenv
anddlopen
from C code, for example. You can work-around it by passing an absolute path toCDLL
, settingLD_LIBRARY_PATH
prior to running your main code in a wrapper script, and no doubt various other ways.See here for more explanation: https://stackoverflow.com/questions/856116/changing-ld-library-path-at-runtime-for-ctypes/4326241.
This issue should be closed.