解决reticulate报错:如何使其绑定Miniconda Python而非系统Python?
加载reticulate包时出现错误:
Error: '/usr/bin/python3.10' was not built with a shared library. reticulate can only bind to copies of Python built with '--enable-shared'.
已通过reticulate::install_miniconda()安装Miniconda并创建basenv环境,执行use_python("/home/asma.ait/.local/share/r-miniconda/envs/basenv/bin/python", required = TRUE)后,py_config()显示已绑定Miniconda的Python:
python: /home/asma.ait/.local/share/r-miniconda/envs/basenv/bin/python libpython: /home/asma.ait/.local/share/r-miniconda/envs/basenv/lib/libpython3.8.so pythonhome: /home/asma.ait/.local/share/r-miniconda/envs/basenv:/home/asma.ait/.local/share/r-miniconda/envs/basenv version: 3.8.20
但重启RStudio并在.Rprofile中设置Sys.setenv(RETICULATE_PYTHON = "/home/asma.ait/.local/share/r-miniconda/envs/basenv/bin/python")后,仍出现系统Python的报错,需要确保reticulate绑定Miniconda的Python而非系统Python。
1. 修正.Rprofile的配置逻辑
替换单纯设置环境变量的代码,改用更直接的conda环境绑定命令,将以下内容写入.Rprofile(优先项目根目录下的.Rprofile,其次用户主目录~/.Rprofile):
library(reticulate) use_condaenv("basenv", required = TRUE)
use_condaenv会直接定位Miniconda下的指定环境,比环境变量设置更可靠,避免路径解析偏差。
2. 清除reticulate的缓存
reticulate会缓存旧的Python环境信息,需手动清理:
- 在R中执行:
reticulate::py_disconnect() unlink(reticulate:::py_cache_dir(), recursive = TRUE) - 完全关闭并重启RStudio
3. 配置RStudio全局Python解释器
- 打开RStudio:
Tools -> Global Options -> Python - 在
Select a Python interpreter中手动选择Miniconda环境的Python路径:/home/asma.ait/.local/share/r-miniconda/envs/basenv/bin/python - 勾选
Set as default,重启RStudio生效
4. 验证绑定结果
重启R后执行以下命令,确认输出路径均指向Miniconda的basenv环境:
library(reticulate) py_config()
内容的提问来源于stack exchange,提问作者Asma

