Tuesday, May 6, 2008

Python for remote control

Python comes with an extensive standard library. One of the modules in the library is called 'subprocess.' This link provides a fairly detailed view of how it works. I will just give a simple example.

Suppose I have a script running in Python and I want to plot some data in R. Perhaps I am doing this repetitively, so naturally I'd like to automate the R interaction. After constructing a list holding the text for the R commands, I just do something like this:


import os, subprocess

FH = open('.temp.Rcode.txt','w')
FH.write('\n'.join(L))
FH.close()

cmd = 'R CMD BATCH ' + os.getcwd()
cmd += '/' + '.temp.Rcode.txt'
obj = subprocess.call(cmd, shell=True)

os.remove('.temp.Rcode.txt')
os.remove('.temp.Rcode.txt.Rout')


I build a text file containing a set of R commands and then I pass it to the R interpreter using subprocess. The file is invisible in the directory because it starts with '.' A nice addition to this example would be to monitor the return code for the process (success or failure) or to wait for the subprocess to finish, in case I need to use the results for something else. The variable obj in the above example contains the return code. To wait, the object returned by subprocess.Popen(cmd, shell=True) has a method wait() which pauses execution until the process is terminated.