ivbsd1
ivbsd1

Reputation: 93

Calling Python from Matlab - how to debug Python code?

I'm working on system which written mostly in Matlab and partially in Python. Python scripts are called from Matlab. I'm looking for convenient way to debug Python code, called from Matlab, with some IDE (like PyCharm).

I'll be glad to receive advice if it is possible and how. Windows 10, Matlab R2018b, Python 3.6

Upvotes: 4

Views: 1600

Answers (1)

Paolo
Paolo

Reputation: 25999

Here's a solution to debug your Python code, executed from MATLAB, in Microsoft Visual Studio.

This solution was tested on Windows 10, with Python 3.6, MATLAB R2020a and Visual Studio 2015.


Create your .py file:

# mymod.py
"""Python module demonstrates passing MATLAB types to Python functions"""
def search(words):
    """Return list of words containing 'son'"""
    newlist = [w for w in words if 'son' in w]
    return newlist


def theend(words):
    """Append 'The End' to list of words"""
    words.append('The End')
    return words

In MATLAB, import the module and create a dummy list:

>> mod = py.importlib.import_module('mymod');
>> N = py.list({'Jones','Johnson','James'});

Open Visual Studio and create a new Python project from existing code. Then, select Attach to Process from the Debug menu:

enter image description here

Search for MATLAB:

enter image description here

select the MATLAB process and attach.

Place a breakpoint in your code:

enter image description here

Now go back to MATLAB and invoke the function:

>> py.mymod.search(N)

MATLAB command window will halt. Go to Visual Studio and debug your code:

enter image description here

Upvotes: 5

Related Questions