Skip to content
Advertisement

Passing arguments to a R script from a JuPyter notebook on a Mac and vice versa?

I have a JuPyter notebook (in Python), and looking to pass a list of arguments into a R program (stored separately in the same directory). After the R program is executed, it will then pass the results back to the JuPyter notebook.

I am on macOS.

So my questions are the following:

  1. How do I pass arguments from JuPyter (Python) to R? I have tried using subprocess.Popen, but it did not seemed to work.
    command = "/Library/Frameworks/R.framework/Resources/bin/R"
    script = "/Users/me/Desktop/rProgram.R"
    args = [1,2,3] # some arguments to pass to R
    cmd = [command, script] + args
    p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    results = p.communicate()

It seems the program did not run. If I print results, I get:

ARGUMENT '/Users/me/Desktop/rProgram.R' __ignored__nn", b"Fatal error: you must specify '--save', '--no-save' or '--vanilla'n")

  1. My second question is, how do I do the same to get the R program to pass back some of its variables back to Python in JuPyter? Or equivalently, how do I get Python to grab these variables from the R program?

Advertisement

Answer

Found out it was a few errors in my directory above. On a Mac, the Rscript path is given as /Library/Frameworks/R.framework/Versions/Current/Resources/Rscript. It seems like the path I had in my original code above will not run an instance of R.

  1. On the Python side :
command = "/Library/Frameworks/R.framework/Versions/Current/Resources/Rscript"
script =  "/Users/me/Desktop/rProgram.R"
args = [1,2,3] # some arguments to pass to R
cmd = [command, script] + args

x = subprocess.check_output(cmd, universal_newlines = True, stderr = subprocess.STDOUT)

The x is the required argument passed back from the rProgram.R script.

  1. On the R side :
# Retrieve arguments from Python
args <- commandArgs(trailingOnly = TRUE)

# Perform some functions
some.value <- some.function(args)

# Passing the value back to Python
cat(some.value)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement