You can use Microsoft's Visual Studio Code (VS Code) to debug your Python code with MATLAB's Python Interface. This process is applicable to both Windows and Linux/Mac.
- See Getting Started with Python in VS Code for instructions on how to install Visual Studio Code, set up a Python project, select a Python interpreter, and create a "launch.json" file. Be sure to select the Python interpreter that you will use in MATLAB.
- Install the "debugpy" module with the Python (main or virtual) executable that you will use in MATLAB and VS Code.
python -m pip install debugpy
If you are using a virtual environment, be sure to activate the virtual environment before running the install command. - Set up your Python environment in MATLAB using "pyenv". Specify the same Python (main or virtual) executable that you are using in VS Code and select the desired "ExecutionMode" ("InProcess" or "OutOfProcess").
- Note that 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
In VS Code, add the following line of code to the top of your Python module, then add breakpoints.
In this example, the port number is specified as "5678". Generally, you can choose any accessible port in the range 1024–65535, as long as it isn't in use or blocked for security reasons.
"launch.json" file
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to debugpy",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678 // Select any accessible and permissable port
},
"justMyCode": true // to only debug the script from user and not through the Python libraries
}
]
}
Configure and launch the "pydebug" server on the same port as specified in the "launch.json" file.
>> py.debugpy.configure(struct("python", pyenv().Executable))
>> py.debugpy.listen({"0.0.0.0",int32(5678)})
In VS Code, select "Run and Debug" (Ctrl+Shift+D), then select the arrow to Start Debugging (F5). The VS Code debug adapter will attach to the server launched in MATLAB.
For the example with "mymod.py", run the following commands from MATLAB.
N = py.list({'Jones','Johnson','James'});
names = py.mymod.search(N)
Execution should stop in VS Code at the first breakpoint. In VS Code, press "Continue" to go to the next breakpoint.
Notes
- If the Python module was edited 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.