0

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?

nba2020
  • 618
  • 1
  • 8
  • 22
  • what platform/OS are you working on? IOS? unix? – Onyambu Feb 13 '20 at 17:01
  • If you look under `~/AppData/Local/r-miniconda` for the `conda` executable, can you then run `conda install requests`? I don't have that distro of miniconda here so I cannot test it easily, but that seems like one reasonable approach. Another (perhaps more of a "best practice") would be to use a virtual environment and make sure the packages you need are installed and maintained. – r2evans Feb 13 '20 at 17:05
  • @Onyambu Windows, since I think ``C:/...`` is exclusive to Windows. Correct me if I am wrong. – Gainz Feb 13 '20 at 17:06
  • sorry my bad. I should have noticed that!! You are right – Onyambu Feb 13 '20 at 17:10
  • 1
    I suggest that you need to read https://rstudio.github.io/reticulate/articles/python_packages.html, where they discuss (*with examples*) how to deal with python packages when using `reticulate`. – r2evans Feb 13 '20 at 17:44

2 Answers2

2

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")
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

You need to install the python module requests before.

If you have installed python, you should have installed pip with it. You can install the module by running pip install requests in command line.

Jrm_FRL
  • 1,394
  • 5
  • 15