Wed Jan 6 12:47:50 EST 2010

Executing Python from Within MATLAB

Today I figured out a way to execute python code from within MATLAB. This wil work on OS-X and Linux and a variant should work under Windows – depending no your python installation. Here’s how it works.

First create the following bash script:

#!/bin/bash
# 
# Val Schmidt
# CCOM/JHC
# Jan 2010
#
# A script to provide a wrapper for execution of python from MATLAB.
PYTHONCODE=/Users/vschmidt/svnsandbox/Gavia/python
/usr/bin/env python $PYTHONCODE/$@

Be sure to modify the PYTHONCODE variable to point to the directory of python scripts you want to execute. Make the script executable (chmod +x executepy.sh) and put it in your path somewhere.

From within MATLAB you can execute your script like this:

unix('source ~/.bash_profile; executepy.sh pythonscript args')

Where pythonscript is the python script you want to execute and args are it’s arguments. It is assumed here that.bash_profile contains your PATH definition (or redefinition). You may have to modify that. You could also modify your PATH on the fly rather than the source statement above if there are things in .bash_profile you don’t want MATLAB’s shell to execute.

This method doesn’t return anything to MATLAB directly. I'm not aware of a way to do that, other than saving the results of your python script to a file that MATLAB can natively read in a subsequent command. (See scipy.io.savemat.)


Posted by Val Schmidt | Permanent link | File under: mac, linux, matlab, python