Sunday, July 10, 2011

[pymex] Or you could just use Jython...

I recently discovered an alternative to pymex: using Jython inside the Matlab interpreter. Jython is an implementation of the Python interpreter in Java. The Matlab interpreter allows the importing of Java objects, so all a programmer needs to do is import the Jython interpreter. Here is an example:

>> javaaddpath('C:\Jython25\jython.jar')
>> import org.python.util.PythonInterpreter
>> import org.python.core.*
>> interp = PythonInterpreter()

interp =

org.python.util.PythonInterpreter@22ff0470

>> interp.exec('import sys')
>> interp.exec('print sys')


>> interp.set('a', 42)
>> interp.exec('print a')
42.0

>> a2 = interp.get('a')

a2 =

42.0

Jython is really cool, but it does have a drawback. Modules written in C for CPython are not compatible with Jython. That excludes alot of modules, but that may not bother some people. If you do need to use a CPython module, you can use pymex.

1 comment:

  1. Thanks! This works great for pure Python code. Don't forget to add site-packages to the path, for your custom packages!

    interp.exec('sys.path.append("c:\\jython2.5.3b1\Lib\\site-packages")')

    ReplyDelete