Debug your Python code

Visual Studio provides a comprehensive debugging experience for Python, including attaching to running processes, evaluating expressions in the Watch and Immediate windows, inspecting local variables, breakpoints, footstep in/out/over statements, Set Side by side Statement, and more.

Also come across the following scenario-specific debugging articles:

  • Linux remote debugging
  • Mixed-manner Python/C++ debugging
  • Symbols for mixed-way debugging

Tip

Python in Visual Studio supports debugging without a project. With a stand-alone Python file open, right-click in the editor, select Start with Debugging, and Visual Studio launches the script with the global default environment (run across Python environments) and no arguments. Simply from and so on, you have full debugging support.

To command the environs and arguments, create a project for the code, which is easily done with the From existing Python code project template.

Bones debugging

The bones debugging workflow involves settings breakpoints, stepping through lawmaking, inspecting values, and handling exceptions as described in the post-obit sections.

A debugging session starts with the Debug > Start Debugging command, the Offset push on the toolbar, or the F5 primal. These actions launch your project's startup file (shown in bold in Solution Explorer) with the project'southward active environs and any control-line arguments or search paths that accept been specified in Projection Properties (see Projection debugging options). Visual Studio 2017 version 15.half dozen and afterward alerts you if you don't have a startup file prepare; earlier versions may open up an output window with the Python interpreter running, or the output window briefly appears and disappears. In whatever case, right-click the advisable file and select Fix as Startup File.

Breakpoints

Breakpoints stop execution of code at a marked point and so you lot can inspect the program land. Set breakpoints by clicking in the left margin of the code editor or by right-clicking a line of code and selecting Breakpoint > Insert Breakpoint. A blood-red dot appears on each line with a breakpoint.

Breakpoints appearing in Visual Studio

Clicking the red dot or correct-clicking the line of lawmaking and selecting Breakpoint > Delete Breakpoint removes the breakpoint. Yous tin also disable it without removing information technology using the Breakpoint > Disable Breakpoint command.

Annotation

Some breakpoints in Python tin be surprising for developers who have worked with other programming languages. In Python, the entire file is executable code, then Python runs the file when it'southward loaded to process whatsoever height-level class or function definitions. If a breakpoint has been set, you may discover the debugger breaking function-way through a class declaration. This behavior is correct, fifty-fifty though it'due south sometimes surprising.

Y'all tin can customize the atmospheric condition under which a breakpoint is triggered, such equally breaking only when a variable is set to a certain value or value range. To gear up conditions, right-click the breakpoint's red dot, select Condition, then create expressions using Python code. For full details on this feature in Visual Studio, run into Breakpoint atmospheric condition.

When setting weather, y'all can also set up Action and create a message to log to the output window, optionally continuing execution automatically. Logging a message creates what is called a tracepoint without adding logging lawmaking to your application directly:

Creating a tracepoint with a breakpoint

Step through code

Once stopped at a breakpoint, y'all take various means to step through lawmaking or run blocks of lawmaking before breaking again. These commands are available in a number of places, including the top debug toolbar, the Debug carte du jour, on the right-click context menu in the code editor, and through keyboard shortcuts (though not all commands are in all places):

Characteristic Keystroke Clarification
Go along F5 Runs code until the adjacent breakpoint is reached.
Step Into F11 Runs the next statement and stops. If the next argument is a call to a function, the debugger stops at the start line of the function being chosen.
Step Over F10 Runs the next argument, including making a telephone call to a office (running all its code) and applying any return value. Stepping over allows you to easily skip functions that yous do non demand to debug.
Step Out Shift+F11 Runs code until the finish of the current office, then steps to the calling statement. This command is useful when you don't demand to debug the residuum of the electric current function.
Run to Cursor Ctrl+F10 Runs code up to the location of the caret in the editor. This command allows you to easily skip over a segment of lawmaking that you don't need to debug.
Set Side by side Statement Ctrl+Shift+F10 Changes the current run betoken in the code to the location of the caret. This command allows you lot to omit a segment of code from being run at all, such as when you know the code is faulty or produces an unwanted side-effect.
Evidence Next Argument Alt+Num * Returns you to the next argument to run. This command is helpful if yous've been looking around in your code and don't remember where the debugger is stopped.

Inspect and modify values

When stopped in the debugger, you tin inspect and modify the values of variables. You tin also apply the Watch window to monitor individual variables and custom expressions. (See Inspect variables for general details.)

To view a value using DataTips, but hover the mouse over whatever variable in the editor. Yous can select the value to change it:

DataTips showing in the Visual Studio debugger

The Autos window (Debug > Windows > Autos) contains variables and expressions that are shut to the electric current statement. You can double-click in the value column or select and press F2 to edit the value:

Autos window in the Visual Studio debugger

The Locals window (Debug > Windows > Locals) displays all variables that are in the current scope, which can once more be edited:

Locals window in the Visual Studio debugger

For more on using Autos and Locals, see Inspect variables in the Autos and Locals windows.

The Watch windows (Debug > Windows > Picket > Watch 1-4) permit y'all to enter arbitrary Python expressions and view the results. Expressions are reevaluated for each pace:

Watch window in the Visual Studio debugger

For more on using Watch, encounter Set a spotter on variables using the Watch and QuickWatch windows.

When inspecting a string value(str, unicode, bytes, and bytearray are all considered strings for this purpose), a magnifying glass icon appears on the right side of the value. Selecting the icon displays the unquoted string value in a popup dialog, with wrapping and scrolling, which is useful for long strings. In add-on, selecting the drop-down arrow on the icon allows yous to select patently text, HTML, XML, and JSON visualizations:

String visualizers in the Visual Studio debugger

HTML, XML, and JSON visualizations appear in carve up popup windows with syntax highlighting and tree views.

Exceptions

If an error occurs in your program during debugging, but you don't have an exception handler for it, the debugger breaks at the point of the exception:

Exception popup in the Visual Studio debugger

At this point you tin can inspect the plan state, including the telephone call stack. However, if y'all attempt to step through the code, the exception continues being thrown until it's either handled or your program exits.

The Debug > Windows > Exception Settings card command brings up a window in which yous can aggrandize Python Exceptions:

Exceptions window in the Visual Studio debugger

The checkbox for each exception controls whether the debugger ever breaks when it's raised. Cheque this box when you lot want to break more than often for a particular exception.

Past default, almost exceptions break when an exception handler cannot be found in the source lawmaking. To change this behavior, right-click whatsoever exception and modify the Continue When Unhandled in User Lawmaking option. Clear this box when you want to break less often for an exception.

To configure an exception that doesn't appear in this list, select the Add button to add information technology. The name must friction match the full proper name of the exception.

Projection debugging options

By default, the debugger starts your program with the standard Python launcher, no control-line arguments, and no other special paths or weather. Startup options are changed through the project'south debug properties accessed by right-clicking your projection in Solution Explorer, selecting Properties, and selecting the Debug tab.

Project debug properties in the Visual Studio debugger

Launch mode options

Pick Description
Standard Python launcher Uses debugging lawmaking written in portable Python that is compatible with CPython, IronPython, and variants such as Stackless Python. It provides the all-time experience for debugging pure Python lawmaking. When you attach to a running python.exe process, this launcher is used. This launcher likewise provides mixed-mode debugging for CPython, allowing you to step seamlessly between C/C++ code and Python code.
Spider web launcher Starts your default browser on launch and enables debugging of templates. See the Web template debugging section for more information.
Django Web launcher Identical to the Web launcher and shown only for backwards compatibility.
IronPython (.NET) launcher Uses the .Internet debugger, which only works with IronPython only allows for stepping betwixt any .NET language project, including C# and VB. This launcher is used if y'all attach to a running .NET procedure that is hosting IronPython.

Run options (search paths, startup arguments, and environment variables)

Selection Clarification
Search Paths These values lucifer what's shown in the project's Search Paths node in Solution Explorer. You lot tin modify this value hither, simply it'due south easier to use Solution Explorer that lets you scan folders and automatically converts paths to relative class.
Script Arguments These arguments are added to the command used to launch your script, appearing afterwards your script'southward filename. The start detail here is available to your script as sys.argv[1], the second equally sys.argv[ii], and and then on.
Interpreter Arguments These arguments are added to the launcher command line before the name of your script. Common arguments hither are -W ... to control warnings, -O to slightly optimize your program, and -u to employ unbuffered IO. IronPython users are likely to use this field to laissez passer -X options, such equally -X:Frames or -X:MTA.
Interpreter Path Overrides the path associated with the current environment. The value may be useful for launching your script with a not-standard interpreter.
Environment Variables In this multi-line text box, add entries of the form <NAME>=<VALUE>. Because this setting is applied last, on height of any existing global environment variables, and later PYTHONPATH is set co-ordinate to the Search Paths setting, it can be used to manually override whatever of those other variables.

There are two interactive windows you tin utilise during a debugging session: the standard Visual Studio Immediate window, and the Python Debug Interactive window.

The Immediate window (Debug > Windows > Immediate) is used for quick evaluation of Python expressions and inspection or assignment of variables within the running program. See the general Firsthand window article for details.

The Python Debug Interactive window (Debug > Windows > Python Debug Interactive) is richer as information technology makes the full Interactive REPL experience available while debugging, including writing and running code. It automatically connects to any procedure started in the debugger using the Standard Python launcher (including processes attached through Debug > Adhere to Procedure). It's not, yet, available when using mixed-mode C/C++ debugging.

Python Debug Interactive window

The Debug Interactive window supports special meta-commands in add-on to the standard REPL commands:

Control Arguments Description
$continue, $cont, $c Starts running the program from the current statement.
$down, $d Move the current frame one level downwardly in the stack trace.
$frame Displays the current frame ID.
$frame frame ID Switches the current frame to the specified frame ID.
$load Loads commands from file and executes until complete
$proc Displays the current process ID.
$proc process ID Switches the current process to the specified procedure ID.
$procs Lists the processes currently being debugged.
$stepin, $footstep, $s Steps into the adjacent office telephone call, if possible.
$stepout, $return, $r Steps out of the current part.
$stepover, $until, $unt Steps over the side by side function call.
$thread Displays the current thread ID.
$thread thread ID Switches the current thread to the specified thread ID.
$threads Lists the threads currently being debugged.
$upwards, $u Move upwards the current frame one level in the stack trace.
$where, $due west, $bt Lists the frames for the current thread.

The standard debugger windows such as Processes, Threads, and Call Stack aren't synchronized with the Debug Interactive window. Changing the active process, thread, or frame in the Debug Interactive window doesn't affect the other debugger windows. Similarly, changing the active process, thread, or frame in the other debugger windows doesn't touch the Debug Interactive window.

Use the legacy debugger

Visual Studio 2017 versions xv.viii and later use a debugger based on ptvsd version 4.1+. Visual Studio 2019 versions 16.5 and afterward use a debugger based on debugpy. These versions of the debugger are compatible with Python 2.7 and Python three.five+. If you're using Python 2.6, iii.ane to 3.4, or IronPython, Visual Studio shows the error, Debugger does non support this Python environs:

Debugger does not support this Python environment error when using the debugger

In these cases, you must employ the older debugger (which is the default in Visual Studio 2017 versions 15.vii and earlier). Select the Tools > Options menu command, navigate to Python > Debugging, and select the Employ legacy debugger option.

If you lot've installed an older version of ptvsd in the current environment (such as an before 4.0.x version, or a 3.x version required for remote debugging), Visual Studio may show an fault or alarm.

The error, Debugger parcel could non be loaded, appears when yous've installed ptvsd 3.x:

Debugger package could not be loaded error when using the debugger

In this case, select Utilise the legacy debugger to prepare the Use legacy debugger option, and restart the debugger.

The alert, Debugger package is outdated, appears when you've installed an earlier iv.x version of ptvsd:

Debugger package is outdated warning when using the debugger

Of import

Although y'all may choose to ignore the warning for some versions of ptvsd, Visual Studio may non piece of work correctly.

To manage your ptvsd installation:

  1. Navigate to the Packages tab in the Python Environments window.

  2. Enter "ptvsd" in the search box and examine the installed version of ptvsd:

    Checking the ptvsd version in the Python Environments window

  3. If the version is lower than 4.1.1a9 (the version bundled with Visual Studio), select the X to the right of the package to uninstall the older version. Visual Studio and then uses its bundled version. (You can also uninstall from PowerShell using pip uninstall ptvsd.)

  4. Alternately, you lot can update the ptvsd package to its newest version by post-obit the instructions in the Troubleshooting section.

Troubleshooting

For Visual Studio 2019 (Version 16.4 and before) upgrade ptvsd

If you take issues with the debugger, first upgrade your version of the debugger as follows:

  1. Navigate to the Packages tab in the Python Environments window.

  2. Enter ptvsd --upgrade in the search box, and so select Run command: pip install ptvsd --upgrade. (You can as well apply the same control from PowerShell.)

    Giving the ptvsd upgrade command in the Python Environments window

    If bug persist, please file an issue on the PTVS GitHub repository.

    Notation

    For Visual Studio 2019 version 16.5 and later, debugpy is part of the Visual Studio Python workload and is updated along with Visual Studio.

Enable debugger logging

In the course of investigating a debugger issue, Microsoft may ask you to enable and collect debugger logs that help in diagnosis.

The post-obit steps enable debugging in the current Visual Studio session:

  1. Open up a command window in Visual Studio using the View > Other Windows > Control Window menu command.

  2. Enter the post-obit command:

                      DebugAdapterHost.Logging /On /OutputWindow                                  
  3. Start debugging and get through whatever steps are necessary to reproduce your issue. During this time, debug logs appear in the Output window under Debug Adapter Host Log. You can then copy the logs from that window and paste into a GitHub issue, email, etc.

    Debugger logging output in the Output window

  4. If Visual Studio stops responding or you lot aren't otherwise able to access the Output window, restart Visual Studio, open a command window, and enter the post-obit control:

                      DebugAdapterHost.Logging /On                                  
  5. Start debugging and reproduce your issue over again. The debugger logs can then exist establish in %temp%\DebugAdapterHostLog.txt.

Encounter also

For complete details on the Visual Studio debugger, see Debugging in Visual Studio.