view test_script_path.py @ 8:a303f3ffa153 draft default tip

Uploaded
author nanette
date Wed, 21 Aug 2013 07:05:54 -0400
parents b41fc3e15949
children
line wrap: on
line source

"""
@summary: GO enrichment analysis (hotspots)
@author: nanette.coetzer@gmail.com
@version 5

"""
import optparse, sys
import subprocess
import tempfile
import os, re

def stop_err( msg ):
    sys.stderr.write( "%s\n" % msg )
    sys.exit()
 
def __main__():
    #Parse Command Line
    parser = optparse.OptionParser()
    parser.add_option("-i", "--input1", default=None, dest="input1", 
                      help="genes")
    parser.add_option("-o", "--output1", default=None, dest="output1", 
                      help="star genes")
    parser.add_option("-p", "--output2", default=None, dest="output2", 
                      help="plot")
    parser.add_option("-m", "--myflag", default=None, dest="myflag", 
                      help="star genes")
    
    (options, args) = parser.parse_args()

    try:
        open(options.input1, "r").close()
    except TypeError, e:
        stop_err("You need to supply the Gene Universe file:\n" + str(e))
    except IOError, e:
        stop_err("Can not open the Gene Universe file:\n" + str(e))


    ##########################################################
    
    infile = open(options.input1,"r")
    inlist = []
    for line in infile:
        inlist.append(line.strip())
    infile.close()
    outfile = open(options.output1,"w")
    for l in inlist:
	outfile.write("* "+str(l)+"\n")
    outfile.write("--- TEST ---" + "\n")
    outfile.write(options.myflag + "\n")
    outfile.write("--- TEST ---" + "\n")
    outfile.close()
    
    ##########################################################
    
    # Create temp direcotry
    tempdir = tempfile.mkdtemp()
    fixdir = options.myflag

    # copy INPUT file to the temp directory
    # create R script => save in temp directory
    # generate new header 
    new_script = open(tempdir+"/new_script.r","w")
    header = "setwd(\"%s\")" %tempdir
    new_script.write(header+"\n")
    
    # add script body
    script = open(fixdir+"/r_plot.r","r")
    for line in script:
        new_script.write(line.strip()+"\n")
    new_script.close()
    
    # run R script from temp directory
    s = "R CMD BATCH %s/new_script.r out.txt" %tempdir
    subprocess.call(s, shell=True)
    
    os.system("mv %s/plot.pdf %s" %(tempdir,options.output2))
       
    ##############################################
    
if __name__=="__main__": 
    __main__()