Search code examples
pythonrreticulate

Calling Python from R with reticulate package


I want to execute a Python script in R. I've installed reticulate and tested that a Python version has correctly initialized in my R session.

py_config()

returns the following

python:         C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
libpython:      C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
pythonhome:     C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate
version:        3.6.10 |Anaconda, Inc.| (default, Jan  7 2020, 15:18:16) [MSC v.1916 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
numpy_version:  1.18.1

Now, when I call the Python script

py_run_file("PythonScript.py")

I hit the following error in R

Error in py_run_file_impl(file, local, convert) : 
  ModuleNotFoundError: No module named 'requests'

I understand that I need to install requests package but how do I make this in the specific Python version I've initialized?


Solution

  • You could write a function that collects the missing packages and installs them:

    run_python_file <- function(python_file){
        a = try(reticulate::py_run_file(python_file),silent=TRUE)
        if(inherits(a,"try-error")& grepl("ModuleNotFoundError",a)){
            system(sprintf("python -m pip install %s",gsub(".* |\\W","",c(a))))
            run_python_file(python_file)
          }
        else a
       }
    run_python_file("PythonScript.py")