2

i am executing a r script from python and i want the output to be available in the python variable. how can i do that?

python script:

import subprocess 

def runR(id, lat, long):
    value = subprocess.popen("C:/R/R-3.2.0/bin/Rscript      E:/Personal/python/script.R --args "+id+" "+lat+" "+long , shell=True)
    print value

R script :

a = "Hello";

I want Hello to be availabe on the python variable value.

5
  • docs.python.org/dev/library/… Commented Jul 13, 2015 at 15:02
  • why not define the value variable by itself so it will be available for the session instead of in the function?> Commented Jul 13, 2015 at 15:02
  • Cheaters way: Run the program, write data to a local text file, then access that file from Python :P Commented Jul 13, 2015 at 15:38
  • That's how I once tried transferring info from Python to PHP/JavaScript Commented Jul 13, 2015 at 15:38
  • This SO post looks like it answers your question: stackoverflow.com/questions/4846891/… Commented Jul 13, 2015 at 15:48

2 Answers 2

4

You could use rpy2:

import rpy2.robjects as robjects

robjects.r('''
a = "Hello";
''')
a = robjects.r['a']

As an alternative, you could rewrite your R script so that it would dump its result to stdout in some well-known format such as json, then run it using subprocess module, and parse the result:

#!/usr/bin/env python
import json
import subprocess

id, lat, long = 1, 40, 74 
out = subprocess.check_output(r"C:\R\R-3.2.0\bin\Rscript.exe "
                              r"E:\path\to\script.R --args "
                               "{id} {lat} {long}".format(**vars()))
data = json.loads(out.decode('utf-8'))

Note: no need to use shell=True on Windows if you use the full path to the executable here.

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

Comments

-1

You can modify the following example by your need.

a.py:

print 'hello'

b.py:

import subprocess
result = subprocess.check_output(["python", "a.py"])
print result.strip() + 'world'

Output of b.py:

helloworld

2 Comments

r script is just an example that i gave. I need to execute the r code and get the answer in python
You could run the program, write all the data to a text file, then access that file from Python

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.