- If the Python module was edited with the debug marker after being invoked by MATLAB, it may be necessary to restart MATLAB (for "InProcess" mode) or use "terminate(pyenv") (for "OutOfProcess" mode)
- The MATLAB process must be attached to the VS Code debugger before the module that contains your breakpoints is loaded in MATLAB. Using the example above,
How can I debug Python code using MATLAB's Python Interface and Visual Studio Code
조회 수: 111 (최근 30일)
이전 댓글 표시
How can I debug my Python code using MATLAB's Python Interface and Visual Studio Code?
채택된 답변
MathWorks Support Team
2024년 9월 23일
편집: MathWorks Support Team
2024년 9월 23일
You can use Microsoft's Visual Studio Code (VS Code) to debug your Python code with MATLAB's Python Interface. This process is illustrated in the steps below and is applicable to both Windows and Linux/Mac.
Important Note:
For R2022b, and later, the process outlined below only works when the "ExecutionMode" is set to "OutOfProcess".
1. Install VS Code and create a project.
See this tutorial for instructions on how to install Visual Studio Code, set up a Python project, select a Python interpreter, and create a
"launch.json" file. In this article we will illustrate the debugging steps using an example taken from the MATLAB documentation: Call User-Defined Python Module.
# 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
2. In a terminal, install the
"debugpy" module using, for example,
python -m pip install debugpy
3. In VS Code, add the following debugging code to the top of your Python module.
import debugpy
debugpy.debug_this_thread()
These lines have been added in the example code below.
# mymod.py
"""Python module demonstrates passing MATLAB types to Python functions"""
import debugpy
debugpy.debug_this_thread()
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
m.foo()
4. Configure the
"launch.json" file to select and attach to MATLAB using the code below.
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to MATLAB",
"type": "python",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
NOTE: Ubuntu users may need to change the value of the
"ptrace" variable using the command below.
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
Be aware that this changes the value globally and has security implications. Best practice is to restore this value to it's original value using
$ echo 1 | sudo tee /proc/sys/kernel/yama/ptrace_scope
5. Add breakpoints to your code.
In this example, we set a breakpoint on line 9 ("newlist = ..."), before the "return" statement.
6. Set up your Python environment in MATLAB and get the ProcessID number.
>> pyenv
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe"
Library: "C:\Users\username\AppData\Local\Programs\Python\Python39\python39.dll"
Home: "C:\Users\username\AppData\Local\Programs\Python\Python39"
ProcessID: "26840"
ExecutionMode: InProcess
In this example, the "ExecutionMode" is set to "InProcess". If you see "Status: NotLoaded", execute any Python command to load the Python interpreter (for example ">> py.list") then execute the "pyenv" command to get the "ProcessID" for the MATLAB process.
7. Attach the MATLAB process to VS Code.
In VS Code, select "Run and Debug" (Ctrl+Shift+D), then select the arrow to Start Debugging (F5). In this example, the green arrow has the label "Attach to MATLAB". Note that this corresponds to the value of the "name" parameter that you specified in the "launch.json" file. Type "matlab" in the search bar of the dropdown menu and select the "MATLAB.exe" process that matches the "ProcessID" from the output of the pyenv command. Note that if you are using "OutOfProcess" execution mode, you will need to search for a "MATLABPyHost.exe" process.
8. Invoke the Python search function from MATLAB.
>> N = py.list({'Jones','Johnson','James'});
>> py.mymod.search(N)
Execution should stop in VS Code at the breakpoint.
NOTES:
N = py.list({'Jones','Johnson','James'});
% Attach MATLAB process to VS Code debugger before doing this next step
m = py.importlib.import_module('mymod');
names = m.search(N)
댓글 수: 1
Lucademicus
2024년 5월 15일
I receive the error "Timed out waiting for debug server to connect."
Could this be related to the fact that my VSCode can not connect to MATLAB anymore ("MATLAB: Not Connected") since some update of MATLAB?
I'm on R2023b update 7
추가 답변 (1개)
Grace Kepler
2024년 9월 24일
This timeout error may occur when running "InProcess" in releases R22b, and later. Please close and reopen MATLAB and switch the "ExecutionMode" to "OutOfProcess".
If you get this error while running "OutOfProcess", try the following: 1) terminate the Python process in MATLAB (">> terminate(pyenv)"). 2) Close and reopen VS Code. 3) Follow the steps 7 and 8 in the article, above.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!