Is it possible to change environment variables of current process?
More specifically in a python script I want to change LD_LIBRARY_PATH so that on import of a module ‘x’ which depends on some xyz.so, xyz.so is taken from my given path in LD_LIBRARY_PATH
is there any other way to dynamically change path from where library is loaded?
Edit: I think I need to mention that I have already tried thing like
os.environ[“LD_LIBRARY_PATH”] = mypath
os.putenv(‘LD_LIBRARY_PATH’, mypath)
but these modify the env. for spawned sub-process, not the current process, and module loading doesn’t consider the new LD_LIBRARY_PATH
Edit2, so question is can we change environment or something so the library loader sees it and loads from there?
The reason
doesn’t work is simple: this environment variable controls behavior of the dynamic loader (
ld-linux.so.2on Linux,ld.so.1on Solaris), but the loader only looks atLD_LIBRARY_PATHonce at process startup. Changing the value ofLD_LIBRARY_PATHin the current process after that point has no effect (just as the answer to this question says).You do have some options:
A. If you know that you are going to need
xyz.sofrom/some/path, and control the execution of python script from the start, then simply setLD_LIBRARY_PATHto your liking (after checking that it is not already so set), and re-execute yourself. This is whatJavadoes.B. You can import
/some/path/xyz.sovia its absolute path before importingx.so. When you then importx.so, the loader will discover that it has already loadedxyz.so, and will use the already loaded module instead of searching for it again.C. If you build
x.soyourself, you can add-Wl,-rpath=/some/pathto its link line, and then importingx.sowill cause the loader to look for dependent modules in/some/path.