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

查看:2706
本文介绍了在导入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(),但无效。

推荐答案

我会使用:

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之前进行设置:在运行时更改LD_LIBRARY_PATH ctypes

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天全站免登陆