Cython无法找到共享对象文件
我正在尝试从Cython链接到我自己的C库,按照我在网上找到的指示,包括这个答案:
I am trying to link to my own C library from Cython, following the directions I've found on the web, including this answer:
我正在通过Spyder运行IPython。
I am running IPython through Spyder.
我的setup.py看起来像这样:
My setup.py looks like this:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy as np
setup(
ext_modules = cythonize(
[Extension("*",["*.pyx"],
libraries =["MyLib"],
extra_compile_args = ["-fopenmp","-O3"],
extra_link_args=["-L/path/to/lib"])
]),
include_dirs = [np.get_include()],
)
文件 libMyLib.so
位于 /路径中/ to / lib
并且它编译得很好。
The file libMyLib.so
is in /path/to/lib
and it compiles fine.
我的IPython配置文件启动文件夹中有一个Python脚本可以执行此操作
I have a Python script in my IPython profile startup folder that does this
try:
os.environ["LD_LIBRARY_PATH"] += ":/path/to/lib"
except KeyError:
os.environ["LD_LIBRARY_PATH"] = "/path/to/lib"
我可以确认这是在运行,因为如果我键入 os.environ [LD_LIBRARY_PATH]
进入IPython解释器,它返回 / path /到/ lib
I can confirm that this is running, because if I type os.environ["LD_LIBRARY_PATH"]
into the IPython interpreter, it returns /path/to/lib
但是当我尝试加载Cython模块(即 import mycythonmodule
)时,我得到:
But when I try to load the Cython module (i.e. import mycythonmodule
) I get:
ImportError: libMyLib.so: cannot open shared object file: No such file or directory
我也尝试将libMyLib.so放在其他地方,看看cython是否会找到它:
I've also tried putting libMyLib.so in other places to see if cython would find it:
- 在运行Python的目录中
- 在Python路径上
- 在与cython模块相同的文件夹中
但它仍然没有找不到共享库。我可以找到它的唯一方法是将它放在 / usr / lib
中,但我不希望它在那里,我希望能够设置库路径。
But it still doesn't find the shared library. The only way I can get it to find the library is by dropping it in /usr/lib
, but I don't want it there, I want to be able to set the library path.
我错过了什么吗?
我如果其他人遇到同样的问题,我会自我回答。看起来答案就在这里:
I'm self-answering, in case anyone else runs into the same problem. Looks like the answers are here:
根据这些答案(和我的经验),链接器在启动python时读取LD_LIBRARY_PATH,因此从python中更改它没有任何有用的效果,至少不是我希望的效果。唯一的解决方案是在设置LD_LIBRARY_PATH的shell脚本中包装python,或者在链接器搜索路径上的某处删除共享对象。
According to these answers (and my experience), the linker reads LD_LIBRARY_PATH when python is launched, so changing it from within python doesn't have any useful effect, at least not the effect I was hoping for. The only solution is to either wrap python in a shell script that sets LD_LIBRARY_PATH, or else drop the shared object somewhere on the linker search path.
有点痛,但是它就是它。
Kind of a pain, but it is what it is.