3

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:

library(reticulate)
use_condaenv( "tensorflow2_latest_p37")

library(tensorflow)
tf$constant("Hello Tensorflow!")

But it failed to recognize the environment:

> 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

What is the right way to do it?

littleworth
  • 4,781
  • 6
  • 42
  • 76

1 Answers1

3

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:

library(tidyverse)
py_bin <- reticulate::conda_list() %>% 
  filter(name == "tensorflow2_latest_p37") %>% 
  pull(python)

Sys.setenv(RETICULATE_PYTHON = py_bin)
library(reticulate)

You can make this permanent by placing this in an .Renviron 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), 
                   ".Renviron", append = TRUE)

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

JBGruber
  • 11,727
  • 1
  • 23
  • 45
  • 1
    Instead of the `writeLines` a more friendly option might be to `usethis::edit_r_profile()` and edit by hand. Or `readr::write_lines` with `append = TRUE` – Rodrigo Zepeda Oct 17 '22 at 18:14
  • Neat! I was not aware that `readr::write_lines` had an append option (I changed the answer). I would not use `usethis::edit_r_profile()` here, since it opens your default `.Rprofile` file in your home directory and I would say setting the `RETICULATE_PYTHON` variable on a project basis makes more sense. – JBGruber Oct 18 '22 at 07:38
  • 2
    @JBGruver `usethis::edit_r_profile(scope = "project")` opens the project's R profile while `usethis::edit_r_profile(scope = "user")` opens the user's – Rodrigo Zepeda Oct 18 '22 at 17:52
  • Wow, I probably should have checked that! – JBGruber Oct 19 '22 at 16:30