Saturday, June 5, 2010

How to launch and terminate Matlab from Python

The recommended way to automate Matlab is to use COM API. However, there are situations where COM is not desired. In this case, the following Python script will launch Matlab, then find the process ID to provide the ability to terminate the process if needed. The reason for this is because occasionally when Matlab is launched from the command line, it shells a new process which is independent of the launching shell. Therefore, to monitor and terminate the Matlab process (say if a script goes awry), the Matlab process and its ID need to be found in the windows process list. Once the process ID is known, it can be treated as any other process by Python.

import wmi
c = wmi.WMI()
import os

os.popen('matlab')

print ‘Matlab launched’
raw_input('Press Enter to continue...')
print ‘Looking for Matlab in process list’
for process in c.Win32_Process(name='matlab.exe'):
    print process.ProcessId, process.Name
    found = True
    if found:
        raw_input('Press Enter to terminate Matlab...')
        process.Terminate()
    else:
        print '!!! Matlab not found...'

 

This code was tested with Matlab 2007b and Python 2.5.1 with PyWin32 and wmi on windows XP.