我有以下现有的 Python 环境:
$ conda info --envs
base * /home/ubuntu/anaconda3
tensorflow2_latest_p37 /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37
我想做的是激活tensorflow2_latest_p37
环境
并在 R 代码中使用它。我尝试了以下代码:
library(reticulate)
use_condaenv( "tensorflow2_latest_p37")
library(tensorflow)
tf$constant("Hello Tensorflow!")
但它未能识别环境:
> library(reticulate)
> use_condaenv( "tensorflow2_latest_p37")
/tmp/RtmpAs9fYG/file41912f80e49f.sh: 3: /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37/etc/conda/activate.d/00_activate.sh: Bad substitution
Error in Sys.setenv(PATH = new_path) : wrong length for argument
In addition: Warning message:
In system2(Sys.which("sh"), fi, stdout = if (identical(intern, FALSE)) "" else intern) :
running command ''/bin/sh' /tmp/RtmpAs9fYG/file41912f80e49f.sh' had status 2
正确的做法是什么?
最佳答案
我发现最可靠的方法是在运行 library(reticulate)
之前设置 RETICULATE_PYTHON
系统变量,因为这将加载默认环境并且更改环境似乎是有点问题。所以你应该尝试这样的事情:
library(tidyverse)
py_bin <- reticulate::conda_list() %>%
filter(name == "tensorflow2_latest_p37") %>%
pull(python)
Sys.setenv(RETICULATE_PYTHON = py_bin)
library(reticulate)
您可以通过将其放置在 .Rprofile
文件中使其永久化。我通常将一个放在项目文件夹中,因此在打开项目时对其进行评估。在代码中,这看起来像这样:
readr::write_lines(paste0("RETICULATE_PYTHON=", py_bin),
".Rprofile", append = TRUE)
或者更简单,使用 usethis::edit_r_profile(scope = "project")
(谢谢@rodrigo-zepeda!)。
关于python - 如何使用 R reticulate 激活现有的 Python 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73967640/