5

I have a problem on how to run a python script from Rstudio?

My initial idea is to grab the python script from a GitHub repository then run it in R, I grabbed python code by using script <- getURL(URL, ssl.verifypeer = FALSE), from RCurl package, I was stuck on how to run Python code without storing the script as a file in the working directory, that is, running the R variable script above directory in Rstudio.

I did know python.load() in _rPython_ package in R could help to run Python script, but it requires the .py file as the first argument. I would like to find a way without storing the Python script as a file.

Thank you in advance if you have any idea of this problem.

9
  • 1
    Can you tell me more about the url from which you're getting the script object? What does the object script look like? Commented Apr 2, 2018 at 20:50
  • 3
    Look into the reticulate package: blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python Commented Apr 2, 2018 at 20:54
  • if you download the script, then you can just say system("python path/to/script.py") Commented Apr 2, 2018 at 21:12
  • @FredBoehm, the URL could be found any python codes from Github repository by cilck Raw button to generate .e.g. link, and script from script <- getURL(URL, ssl.verifypeer = FALSE) is a character vector, it's all the content (codes) in that URL. Commented Apr 2, 2018 at 21:14
  • @lefft thanks and I knew, but I would like to find a way without downloading script. Commented Apr 2, 2018 at 21:17

1 Answer 1

2

Make sure you're running an R Markdown file and have reticulate installed.

Load and configure your Python version:

```{r setup, include = FALSE}
library(reticulate)
use_python("usr/local/bin/python")
```

Then, any python code can be called as follows:

```{python}
# write python
# code here
```

If you create any global python objects and want to use them with R code, simply preface them with py$; e.g. to access a dataframe created with python called my_data in an R chunk:

```{r}
head(py$my_data)
```

More details can be found here.

Sign up to request clarification or add additional context in comments.

2 Comments

Great start. Is there a way to call a script with arguments and just get the stdout of the python script? e.g., py_output <- %run ./mypythonscript.py arg1 arg2 ... ?
I just ran across this: "Sourcing Python scripts — The source_python() function enables you to source a Python script the same way you would source() an R script (Python functions and objects defined within the script become directly available to the R session).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.