用Matlab调用Python - 如何调试Python代码?

4

我正在处理一个主要由Matlab编写且部分使用Python的系统。 Python脚本是从Matlab中调用的。 我正在寻找一种方便的方式来使用一些集成开发环境(如PyCharm)来调试从Matlab中调用的Python代码。

如果可能的话,我将很高兴收到建议以及如何操作。 操作系统为Windows 10,Matlab版本为R2018b,Python版本为3.6。


PyCharm很好,但我无法想象用Matlab打开它会意味着什么。 - Yuval Harpaz
@sardarusama:问题是是否有任何IDE能够通过MATLAB调试Python代码。对于从MATLAB调用的C/C++代码,我们可以使用MSVC“附加到进程”,不知道Python是否有一些类似的概念在这里实际起作用。 - Daniel
你在使用Windows系统吗? - Paolo
@Daniel PyCharm有附加到进程的能力。但是我怎么知道要附加到哪个进程? - ivbsd1
@Paolo 是的,Windows 10 - ivbsd1
1个回答

5
这是一种解决方案,可以在Microsoft Visual Studio中调试由MATLAB执行的Python代码。
该解决方案已在Windows 10上使用Python 3.6、MATLAB R2020a和Visual Studio 2015进行了测试。
创建你的.py文件:
# 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

在MATLAB中,导入模块并创建一个虚拟列表:
>> mod = py.importlib.import_module('mymod');
>> N = py.list({'Jones','Johnson','James'});

打开Visual Studio,并从现有代码创建一个新的Python项目。然后,从调试菜单中选择附加到进程:

enter image description here

搜索 MATLAB:

enter image description here

选择 MATLAB 进程并附加。
在您的代码中设置断点:

enter image description here

现在返回MATLAB并调用该函数:
>> py.mymod.search(N)

MATLAB命令窗口将停止运行。前往Visual Studio调试您的代码:

enter image description here


1
非常感谢。同样的程序也适用于PyCharm! - ivbsd1
@ivbsd1 你在使用哪个版本的Matlab和PyCharm?我尝试了完全相同的过程,但它无法遵守断点。 - Dudas
Pycharm 2019.2.4,Matlab 2019b。它不适用于PyCharm 2020。 - ivbsd1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接