This is possible using the svSocket
package. The package "Implements a simple socket server allowing to connect GUI clients to R" and is not blocking R. Rserve
provides similar capacities and also has libraries for other languages but blocks the R session.
In the main R session:
require('svSocket')
startSocketServer(port=8888)
df = data.frame(var1=1:100,var2=4)
Now you can communicate with the main R session from other R session:
require('svSocket')
con = socketConnection(port=8888)
evalServer(con, ls())
evalServer(con, names(df))
Which lists all the objects in the main R session and returns the names of the data.frame df
.
There are different methods to use this approach from Python or other languages. One possibility is the subprocess
module
args = ['RScript', '--vanilla']
args.extend(['-e', 'require("svSocket")'])
args.extend(['-e', 'con = socketConnection(port=8888)'])
args.extend(['-e', 'evalServer(con, ls())'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
The disadvantage of this approach is that it starts a new R session every time you run this code in Python, which is not very fast. Rserve
has a python client and something similar might be possible for svSocket
(not sure though). The speed is a limitation if you need immediate access to information about objects in the main R workspace. In that you might want to cache information from the main R session in certain intervals and use this cache for whatever you want to do.