更改当前进程环境的 LD_LIBRARY_PATH

问题描述

是否可以更改当前进程的环境变量?

Is it possible to change environment variables of current process?

更具体地说,在 python 脚本中,我想更改 LD_LIBRARY_PATH 以便在导入依赖于某些 xyz.soxyz 的模块x"时.so 取自我在 LD_LIBRARY_PATH 中的给定路径

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?

编辑:我想我需要提到我已经尝试过类似的东西os.environ["LD_LIBRARY_PATH"] = mypathos.putenv('LD_LIBRARY_PATH', mypath)

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)

但是这些修改了环境.对于生成的子进程,而不是当前进程,并且模块加载不考虑新的 LD_LIBRARY_PATH

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,所以问题是我们可以改变环境或其他东西,以便库加载器看到它并从那里加载吗?

Edit2, so question is can we change environment or something so the library loader sees it and loads from there?


解决方案

原因

os.environ["LD_LIBRARY_PATH"] = ...

不起作用很简单:这个环境变量控制动态加载器的行为(Linux 上的ld-linux.so.2ld.so.1Solaris),但加载程序仅在进程启动时查看一次 LD_LIBRARY_PATH.在当前进程之后更改 LD_LIBRARY_PATH 的值没有效果(就像 这个问题说).

doesn't work is simple: this environment variable controls behavior of the dynamic loader (ld-linux.so.2 on Linux, ld.so.1 on Solaris), but the loader only looks at LD_LIBRARY_PATH once at process startup. Changing the value of LD_LIBRARY_PATH in the current process after that point has no effect (just as the answer to this question says).

您确实有一些选择:

You do have some options:

A.如果你知道你将需要 /some/path 中的 xyz.so,并从一开始就控制 python 脚本的执行,那么只需设置 LD_LIBRARY_PATH 根据自己的喜好(在检查它是否尚未设置后),然后重新执行自己.这就是 Java 所做的.

A. If you know that you are going to need xyz.so from /some/path, and control the execution of python script from the start, then simply set LD_LIBRARY_PATH to your liking (after checking that it is not already so set), and re-execute yourself. This is what Java does.

B.您可以通过其绝对路径在导入x.so之前导入/some/path/xyz.so.当你再导入 x.so 时,加载器会发现它已经加载了 xyz.so,并且会使用已经加载的模块而不是再次搜索它.

B. You can import /some/path/xyz.so via its absolute path before importing x.so. When you then import x.so, the loader will discover that it has already loaded xyz.so, and will use the already loaded module instead of searching for it again.

C.如果你自己构建x.so,你可以在其链接行添加-Wl,-rpath=/some/path,然后导入x.so 将导致加载器在 /some/path 中查找依赖模块.

C. If you build x.so yourself, you can add -Wl,-rpath=/some/path to its link line, and then importing x.so will cause the loader to look for dependent modules in /some/path.

相关文章