#!/usr/bin/env python

"""
	Usage: ./runCplexScript.py filename.lp
	
		The cplex_script array below should be edited to your needs, feel free to add or delete
		CPLEX commands from it. 

		Note:
			1. the script will automatically read the file you use as input
			2. all paths you set in the script such as log file location is relative to this script
			3. remember to add \n after each command - it simulates <enter> when interacting with CPLEX
			4. the CPLEX results are located in the log file you've chosen

	
	Written by Ari Bjornsson ari.bjornsson (at) gmail.com - September 2009 
"""


import subprocess
import sys
import os

cplex_script = ['set logfile /xbar/nas1/home4/s08/s081593/cplex.log\n'
		, 'set timelimit 120\n'
		, 'read file.lp'
		, 'optimize\n'
		, 'display problem all\n'
		, 'display solution variables all\n'
		, 'quit\n'
		]

def scr_cplex(lines):
        proc = subprocess.Popen('/usr/local/bin/cplex',
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE
                                )

        for l in lines:
                proc.stdin.write(l)

        proc.communicate()

def main():
	lp_file = ""

	for arg in sys.argv[1:]:
		if str(arg)[-2:] == 'lp':
			lp_file = arg

	if lp_file != "":
		if os.path.isfile(lp_file):
			cplex_script[2] = "read " + lp_file + '\n'
			scr_cplex(cplex_script)
		else:
			print "Input file not found"
			sys.exit
	else:
		print "Script exited without doing anything, check input"
		sys.exit

if __name__ == '__main__':
	main()

