How to activate existing Python environment with R reticulate


I have the following existing Python environments:

$   conda info --envs

base                  *  /home/ubuntu/anaconda3
tensorflow2_latest_p37     /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37

What I want to do is to activate tensorflow2_latest_p37 environment
and use it in R code. I tried the following code:

use_condaenv( "tensorflow2_latest_p37")

tf$constant("Hello Tensorflow!")

But it failed to recognize the environment:

> library(reticulate)
> use_condaenv( "tensorflow2_latest_p37")
/tmp/RtmpAs9fYG/ 3: /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37/etc/conda/activate.d/ 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/' had status 2

What is the right way to do it?


I found the most reliable way is to set the RETICULATE_PYTHON system variable before running library(reticulate), since this will load the default environment and changing environments seems to be a bit of an issue. So you should try something like this:

py_bin <- reticulate::conda_list() %>% 
  filter(name == "tensorflow2_latest_p37") %>% 

Sys.setenv(RETICULATE_PYTHON = py_bin)

You can make this permanent by placing this in an .Rprofile file. I usually place one in the project folder, so it is evaluated upon opening the project. In code this would look like that:

readr::write_lines(paste0("RETICULATE_PYTHON=", py_bin), 
                   ".Rprofile", append = TRUE)

Or even easier, use usethis::edit_r_profile(scope = "project") (thank you @rodrigo-zepeda!).

Answered By – JBGruber

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published