4

I have a python script that I want to run from within R using the reticulate package. I want to assign some variables in R first, and then pass them to the script. Unfortunately when I run the script, I am surprised to see that python can't recognize the variables. What am I missing here? Thanks

Python script (test.py):

print(x)

R code:

library(reticulate)
x <- 5
source_python(test.py)

The error:

Error in py_run_file_impl(file, local, convert) : 
  NameError: name 'x' is not defined
Jacqueline Nolis
  • 1,457
  • 15
  • 22
  • Try: python_run_string("x = 5"); source_python("test.py"); Unfortunately, source_python can only set variables to your R session. It does not read variables unless they are from python code that has been evaluated. – Brian Sep 26 '18 at 21:32

1 Answers1

1

The solution I came up with was to just create a function. So if before my python code was

z = x + 3

My new python code would be:

def add_three(x):
    z = x + 3
    return z

and then I can, in R run:

x <- 5
source_python("test.py")
y <- add_three(x)

and get y as 6.

Jacqueline Nolis
  • 1,457
  • 15
  • 22
  • As exactly what the [docs](https://rstudio.github.io/reticulate/) show. – Parfait Sep 27 '18 at 19:28
  • It does work. However, u passed the parameter to a function to python code. If it means that if one what to pass parameters to a python script, he should call a function? Sometimes, It may not be convenient. Can python script access variables from R code above? – lemmingxuan Jun 20 '21 at 07:19