python - 如何使用 R reticulate 激活现有的 Python 环境

标签 python r tensorflow rstudio reticulate

我有以下现有的 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/

相关文章:

r - 用于查询大数据的 64 位 R 的 32 位数据库驱动程序

r - Quanteda 中的朴素贝叶斯与插入符号 : wildly different results

r - 将表达式与 sprintf 结合起来,在 R 中生成用于 ggplot/plot-labeling 的结果

tensorflow - .tflite模型每次初始化相同的检测框

python - 如何安装最新版本的 TensorFlow 2?

python - 如何根据另一个 DataFrame 的条件从 Multi-Index Dataframe 中选择一个子集

python - 尝试使用 Twitter API 验证应用程序时出现 403 错误

tensorflow - 无法从 'model_lib_v2' 导入名称 'object_detection'

python - brew install python3 没有安装 pip3

python - 使用 python MySQLdb 连接正确处理异常