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
1
  • 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. Commented Sep 26, 2018 at 21:32

1 Answer 1

4

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.

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

2 Comments

As exactly what the docs show.
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?

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.