user2728024
user2728024

Reputation: 1546

Get result to python variable after executing R script

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.

Upvotes: 2

Views: 2300

Answers (2)

jfs
jfs

Reputation: 414159

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.

Upvotes: 4

Sait
Sait

Reputation: 19805

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

Upvotes: -1

Related Questions