代码:
from python import Python
fn f() raises:
# This is equivalent to Python's `import numpy as np`
let np = Python.import_module("numpy")
let a = np.array([1, 2, 3])
print(a)
fn main() raises:
f()
mojo编译后执行,报错:
Mojo/Python interoperability error: Unable to locate a suitable libpython, please set `MOJO_PYTHON_LIBRARY`
==============================================
参考:
https://github.com/modularml/mojo/issues/551
执行命令(查找当前python环境下的libpython位置):
python3 -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))'
ls $(python3 -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))') | grep libpython
解决方法:
echo 'export MOJO_PYTHON_LIBRARY="<full_path_to_libpython.so>"' >> ~/.bashrc
source ~/.bashrc
因此在当前环境配置命令为:
export MOJO_PYTHON_LIBRARY=/home/devil/anaconda3/envs/mojo/lib/libpython3.so
也或者将命令写入 .bashrc 配置文件中:
配置后执行:
/home/devil/anaconda3/lib/python3.9/site-packages/numpy/__init__.py:143: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
from . import _distributor_init
Unhandled exception caught during execution: An error occurred in Python.
考虑到之前配置使当前的python环境失效,重新设置python解释器环境:
conda activate mojo
再次执行,成功:
==============================================
PS:
说明下上面配置的原理,mojo二进制执行程序调用python库其实可以分为编译和执行两个阶段,编译的时候指定libpython3.so的位置就是指定编译后的程序需要调用的lib库是哪个,执行的时候会在当前的lib库搜索路径下进行搜索,因此就需要保证编译时指定的libpython3.so文件和执行时候的搜索的当前python环境是同一个。
==============================================