How can I debug Python code using MATLAB's Python Interface and Visual Studio Code

111 次查看(过去 30 天)

采纳的回答

MathWorks Support Team
编辑: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
For more information and discussion, see this link and this link.
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:
  • 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,
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
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
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.

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by