Using debugger in python

Debug your first Python application

Remember, in the previous tutorial you’ve created and run the Car script? Let’s play a little more with it and modify the average_speed function as follows:

Let’s see what happens when we start our script up, and try to find out the average speed by typing s in the command line:

Error messages

Oops. PyCharm reports a runtime error: a ZeroDivisionError .

Let’s dig a little deeper into our code to find out what’s going wrong. We can use the PyCharm debugger to see exactly what’s happening in our code. To start debugging, you have to set some breakpoints first. To create breakpoints, just click in the gutter

Adding breakpoints

Next, click the icon in the gutter, next to the main clause, and choose Debug ‘Car’ .

Debug command

PyCharm starts a debugging session and shows the Debug tool window

Debug tool window

Click the button to proceed with the script execution and in the Console tab, enter S and press Enter :

Debug tool window: Console tab

Click the button to resume the script execution. The exception is here. Another breakpoint appeared as well: by default PyCharm will halt for any exception that wasn’t caught in your code, and it’ll show an icon of a breakpoint with a lightning bolt.

Exception breakpoint

The debugger also shows the error message. So we’ve found our problem. You can also see in the debugger, that the value self.time is equal to zero:

aself.time is equal to zero

Surrounding code

To avoid running into the same problem again, let’s add an if statement to check whether the time equals zero. To do that, select the statement return self.odometer / self.time in the method average_speed and then press Control+Alt+T ( Code | Surround with ):

Surround code

PyCharm creates a stub if construct, leaving you with the task of filling it with the proper contents.

A stub for surrunding with an if statement

After editing, we get the following:

Results of the surrounded code

Let’s take a closer look to see how the debugger can show your what your code is doing.

Debugging in detail

The Debug tool window shows dedicated panes for frames, variables, and watches, and the console, where all the input and output information is displayed. If you want the console to be always visible, you can drag it to one of the PyCharm window’s edges.

Stepping

If you want to see what your code does line by line, there’s no need to put a breakpoint on every line, you can step through your code.

Let’s see what it looks like to step through our example program: click the button, go to the Console to ask for the car’s average speed (type ‘S’), and we can see that we press our breakpoint.

We can use the stepping toolbar buttons to choose on which line we’d like to stop next.

Stepping toolbar

For example, click the Step Over button and see the blue marker moving to the next line of code:

Stepping over during the debugging

If you click the Step Into button , you will see that after the line action = input(«What should I do? [A]ccelerate, [B]rake, » «show [O]dometer, or show average [S]peed?»).upper() the debugger goes into the file parse.py :

Stepping into during the debugging

However, if you continue using , you’ll see that your application just passes to the next loop:

Debugging: passing to the next loop

If you want to concentrate on your own code, use the Step Into My Code button — thus you’ll avoid stepping into library classes.

Watching

The Add button

PyCharm allows you to watch any variable. Just type the name of the variable you want to watch in the Evaluate and Watch field — let it be my_car.time . Note that code completion is available here. Then click on next to the field.

Watch completion

At first, you see the time equals 0 — it means that the variable is not yet defined:

Watch error

However, when the program execution continues to the scope that defines the variable, the watch gets the following view:

Watched variable gets a value

Inline debugging

You may have noticed another PyCharm feature that makes it easy to see what your code is doing: the inline debugger. As soon as you press any breakpoint, PyCharm shows you the value of many of your variables right in the editor:

Inline debugging

This inline debugging feature is enabled by default. If you don’t see the inline debugging values, check that it’s enabled using the settings icon on the debug toolbar :

Show values inline

Summary

So, you’ve done it! Congrats! Let’s repeat what you’ve done with the help of PyCharm:

  • Found out the origin of the problem
  • Set breakpoints
  • Stepped through your program
  • Created a watch
  • Evaluated an expression

Источник

Part 1. Debugging Python Code

Do you remember the quadratic formula from math class? This formula is also known as the A, B, C formula, it’s used for solving a simple quadratic equation: ax2 + bx + c = 0 . As manually solving quadratic formulas gets boring quickly, let’s replace it with a script.

Copy the following code into a file in your project (though it is recommended to type this code manually):

import math class Solver: def demo(self, a, b, c): d = b ** 2 — 4 * a * c if d > 0: disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b — disc) / (2 * a) return root1, root2 elif d == 0: return -b / (2 * a) else: return «This equation has no roots» if __name__ == ‘__main__’: solver = Solver() while True: a = int(input(«a: «)) b = int(input(«b: «)) c = int(input(«c: «)) result = solver.demo(a, b, c) print(result)

As you see, there is the main clause here. It means that execution will begin with it, let you enter the desired values of the variables a , b and c , and then enter the method demo .

Placing breakpoints

To place breakpoints, just click the gutter next to the line you want your application to suspend at:

Adding a breakpoint

Refer to the section Breakpoints for details.

Starting the debugger session

OK now, as we’ve added breakpoints, everything is ready for debugging.

PyCharm allows starting the debugger session in several ways. Let’s choose one: click in the gutter, and then select the command Debug ‘Solver’ in the popup menu that opens:

debug Python script

The debugger starts, shows the Console tab of the Debug tool window, and lets you enter the desired values:

Debugging console

By the way, in the Debug Console , you can enter the Python commands:

Using a Python prompt in the debug console

Then the debugger suspends the program at the first breakpoint. It means that the line with the breakpoint is not yet executed. The line becomes blue:

Debugging stop st the first breakpoint

On the stepping toolbar of the Debugger tab, click the button, to move to the next breakpoint.

Inline debugging

In the editor, you see the grey text next to the lines of code:

Inline debugging

This is the result of the so-called inline debugging. The first lines show the address of the Solver object and the values of the variables a , b and c you’ve entered.

Note that you can do it in course of the debugger session!

Let’s step!

So, you’ve clicked the button, and now see that the blue marker moves to the next line with the breakpoint.

If you use the stepping toolbar buttons, you’ll move to the next line. For example, click the button. Since the inline debugging is enabled, the values of the variables show in italic in the editor.

Step into

If you click the button, you will see that after the line a = int(input(«a: «)) the debugger goes into the file parse.py :

Stepping into

However, if you continue using the button, you’ll see that your application just passes to the next loop:

Expecting next input

If you want to concentrate on your own code, use the button Step Into My Code — thus you’ll avoid stepping into library classes.

Watching

PyCharm allows you to watch a variable. Just click on the toolbar of the Variables tab, and type the name of the variable you want to watch. Note that code completion is available:

adding a new watch

At first, you see an error — it means that the variable is not yet defined:

Incorrect adding watch

However, when the program execution continues to the scope that defines the variable, the watch gets the following view:

Correst adding watch

Evaluating expressions

Finally, you can evaluate any expression at any time. For example, if you want to see the value of the variable, click the button , and then in the dialog that opens, click Evaluate :

evaluating expressions

PyCharm gives you the possibility to evaluate any expression. For example:

evaluating a math expression

You can enter some commands in the Debug Console to show the variables values. (the icon toggle this mode). For example, you can change the a variable. This change will be shown in the corresponding code in the Editor.

Debugging using the prompt console

Changing format of the decimal variables

In PyCharm debugger, you can preview int variables in the hexadecimal or binary format. This might be particularly helpful when you debug network scripts that include binary protocols.

To change the display format, select one or several int variables in the Variables list, right-click, and select View as | Hex from the context menu.

Content menu to preview decimal values in the hexadecimal format

The format of the variables change both in the list of the variables and in the editor.

Hexadecimal representation of the debuged variables

Summary

This brief tutorial is over — congrats! Let’s repeat what you’ve learnt from it:

  • You’ve refreshed your knowledge of the breakpoints and learnt how to place them.
  • You’ve learnt how to begin the debugger session, and how to show the Python prompt in the debugger console.
  • You’ve refreshed your knowledge about the inline debugging.
  • You’ve tried hands on stepping, watches and evaluating expressions.

The next step is intended for the Professional edition users — this is Debugging Django Templates.

Источник

Читайте также:  Java in place array
Оцените статью