Sunday, September 13, 2009

Using Python to control a Scilab instance

This example shows how to start Scilab, pass it a file to execute, and terminate it if necessary. In this example, Scilab is not in the search path, therefore, the full path to Scilab is necessary.
This example only works on Python 2.6 or later.
"""
StartThreadForSciLab.py
"""

import subprocess

# write scilab script into a file. 
# this will be executed by Scilab

f = open('C:\\tmp\\scilabTest.sce', 'w')
cmds = """printf('hello!')
x = input("Press return to continue:","string")
exit
"""
f.write(cmds)
f.close

# start up Scilab and retain a handle to control and monitor
sciLabProcess = subprocess.Popen(
    '"C:\\Program Files\\scilab-5.1.1\\bin\\WScilex.exe" -f c:\\tmp\\scilabTest.sce ', 
    bufsize=0, 
    executable=None, 
    stdin=None, 
    stdout=None, 
    stderr=None, 
    preexec_fn=None, 
    close_fds=False, 
    shell=False, 
    cwd=None, 
    env=None, 
    universal_newlines=False, 
    startupinfo=None, 
    creationflags=0)
    
# wait for process to exit, or terminate it
while sciLabProcess.poll() is None:
    print 'still running'
    reply = raw_input("Kill process ? (type yes) ")
    if reply.strip()=='yes':
        sciLabProcess.terminate()

Using Python to start a process: Notepad as an example

This examples shows how to start a common process in windows while allowing the Python program to continue and, if needed, terminate the process.
import subprocess

notepadProcess = subprocess.Popen("Notepad")
while notepadProcess.poll() is None:
    print 'still running'
    reply = raw_input("Kill process ? (type yes) ")
    print '>>|'+reply.strip()+'|<<'
    if reply.strip()=='yes':
        print "closing process"
        notepadProcess.terminate()