#!/usr/bin/env python
# Executes an R script
# $Revision: 1.1 $
# paul sorenson oct 2003

CMD = '''"/Program Files/R/rw2001/bin/rterm.exe" --vanilla --slave'''

import logging
log = logging.getLogger('TT')


def RExec(RFile, params = None):
    '''
    Execute an R script - optionally interpolating dict style params.

    Warning, R also accepts %0d style interpolation, if you want to pass
    this to R then your original script must add an additional %.
    Eg:
    png(filename="c:/sosman/testtrack/web/tt%%02d.png", width=640)
    
    This will get passed to R as:
    png(filename="c:/sosman/testtrack/web/tt%02d.png", width=640)
    if you pass in non null params to the function.
    
    If params is not set then no interpolation will take place so raw
    R scripts will pass through unchanged.
    '''
    import popen2
    (r, w, e) = popen2.popen3(CMD)
    rsrc = RFile.read() % params
    log.debug(rsrc)
    w.write(rsrc)
    w.close()
    err = e.read()
    print err
    e.close()
    r.close()
 
def usage():
    print 'usage: python R.py --r-script=<R_script> [--params=<params>]'
    sys.exit(2)
    
if __name__ == "__main__":
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], "p:r:", ["params=", "r-script="])
    except getopt.GetoptError:
        usage()
    scriptname = None
    params = None
    for opt, arg in opts:
        if opt in ('-p', '--params'):
            params = eval(arg)
        elif opt in ('-r', '--r-script'):
            scriptname = arg
    if not scriptname:
        usage()
    print '# script: "%s"  params: "%s"' % (scriptname, params)
    r = file(scriptname, 'r')
    RExec(r, params)
    r.close()

