在 python 中导入之前设置 LD_LIBRARY_PATH [英] Set LD_LIBRARY_PATH before importing in python

查看:20
本文介绍了在 python 中导入之前设置 LD_LIBRARY_PATH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 使用 PYTHONPATH 环境变量来确定它应该在哪些文件夹中查找模块.您可以通过修改 sys.path 来使用它,这对于纯 Python 模块非常有效.但是当一个模块使用共享对象文件或静态库时,它会在 LD_LIBRARY_PATH(在 linux 上)中寻找那些,但这不能轻易改变,而且据我所知是平台相关的.

Python uses the PYTHONPATH environment-variable to determine in which folders it should look for modules. You can play around with it by modifying sys.path, which works nicely for pure Python-Modules. But when a module uses shared object files or static libraries, it looks for those in LD_LIBRARY_PATH (on linux), but this can't be changed as easily and is platform dependent as far as I know.

这个问题的快速修复当然是设置环境变量或调用像 LD_LIBRARY_PATH= 这样的脚本../script.py,但是你必须为你打开的每个新 shell 再次设置它.此外,在我的例子中 .so 文件将始终与 .py 文件在同一目录中,但很可能被移动到另一个绝对路径,所以我我想在每次调用脚本时自动设置它们.

The quick-fix for this problem is of course to set the environment-variable or invoke the script like LD_LIBRARY_PATH=. ./script.py, but then you'll have to set it again for every new shell you open. Also, the .so files in my case will always be in the same directory as the .py file, but may very well be moved to another absolute path, so I'd like to set them automatically every time I invoke the script.

如何编辑 Python 解释器在运行时独立于平台查找库的路径?

我已经尝试过 os.environ['LD_LIBRARY_PATH'] = os.getcwd(),但是没有用.

I already tried os.environ['LD_LIBRARY_PATH'] = os.getcwd(), but to no avail.

推荐答案

更新:请参阅下面的编辑.

UPDATE: see the EDIT below.

我会使用:

import os

os.environ['LD_LIBRARY_PATH'] = os.getcwd()  # or whatever path you want

这仅针对当前进程的执行持续时间/生命周期设置 LD_LIBRARY_PATH 环境变量.

This sets the LD_LIBRARY_PATH environment variable for the duration/lifetime of the execution of the current process only.

看起来需要在启动 Python 之前进行设置:在运行时更改 ctypes 的 LD_LIBRARY_PATH

it looks like this needs to be set before starting Python: Changing LD_LIBRARY_PATH at runtime for ctypes

所以我建议使用包装 .sh(或 .py,如果你坚持)脚本.此外,正如@chepner 指出的那样,您可能需要考虑在标准位置(在 virtualenv 内)安装 .so 文件.

So I'd suggest going with a wrapper .sh (or .py if you insist) script. Also, as @chepner pointed out, you might want to consider installing your .so files in a standard location (within the virtualenv).

另见 从 Python 内部设置 LD_LIBRARY_PATH

这篇关于在 python 中导入之前设置 LD_LIBRARY_PATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆