Search code examples
rvirtualenvreticulate

How can I switch virtualenv from reticulate in R?


In R package reticulate there is a function use_virtualenv but it does not look like I can call it twice with different virtualenvs, second call is always ignored.

Is there a way to deactivate first virtualenv so I can call use_virtualenv("venv2") with the expected behavior?

#initialize
require(reticulate)
virtualenv_create("venv1")
virtualenv_create("venv2")

#call first virtualenv
use_virtualenv("venv1") 
py_config() #show venv1 specs

#call second vrtualenv
use_virtualenv("venv2")
py_config() # still show venv1 specs, I want venv2 here

I think unloadNamespace("reticulate") could work but in my case first call is made by another package...


Solution

  • In short: By restarting the R session! You can't switch virtualenv in reticulate once chosen!

    I tried it (but chose "venv2" first).

    
    > use_python("venv1", T)
    Error in use_python("venv1", T) : 
      Specified version of python 'venv1' does not exist.
    > use_python("~/.virtualenvs/venv1", T)
    ERROR: The requested version of Python ('~/.virtualenvs/venv1') cannot
    be used, as another version of Python
    ('/home/josephus/.virtualenvs/venv2/bin/python') has already been
    initialized. Please restart the R session if you need to attach
    reticulate to a different version of Python.
    Error in use_python("~/.virtualenvs/venv1", T) : 
      failed to initialize requested version of Python
    
    

    So reticulate messages, that one has to start a new session to choose new virtual environment. This must apply to use_virtualenv(<xxx>, T) too, though it is not as verbose as use_python(<xxx>, T).