- Part 1. Debugging Python Code
- Placing breakpoints
- Starting the debugger session
- Inline debugging
- Let’s step!
- Watching
- Evaluating expressions
- Changing format of the decimal variables
- Summary
- Python console
- Actions available in the Python Console
- Working with Python console
- Preview a variable as an array
- Run source code from the editor in console
- Run asyncio coroutines
- Configure Python console settings
- Run several Python consoles
- Manage the command execution queue
- Console tab
- Console toolbar
- Context menu options
- Keyboard shortcuts
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:
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:
The debugger starts, shows the Console tab of the Debug tool window, and lets you enter the desired values:
By the way, in the Debug Console , you can enter the Python commands:
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:
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:
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.
If you click the button, you will see that after the line a = int(input(«a: «)) the debugger goes into the file parse.py :
However, if you continue using the button, you’ll see that your application just passes to the next loop:
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:
At first, you see an error — it means that the variable is not yet defined:
However, when the program execution continues to the scope that defines the variable, the watch gets the following view:
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 :
PyCharm gives you the possibility to evaluate any expression. For example:
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.
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.
The format of the variables change both in the list of the variables and in the editor.
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.
Python console
Python console enables executing Python commands and scripts line by line, similar to your experience with Python Shell.
Actions available in the Python Console
- Type commands and press Enter to execute them. Results are displayed in the same console.
- Use basic code completion Control+Space and tab completion.
- Use the await keyword to run asyncio coroutines.
- Use Up and Down arrow keys to scroll through the history of commands, and execute the required ones.
- Load source code from the editor into console.
- Use the context menu to copy the contents of the console to the clipboard, compare it with the clipboard, or clear the console.
- Use the toolbar buttons to control your session in the console.
- Configure color scheme of the console to meet your preferences. Refer to the section Configure color schemes for consoles for details.
Working with Python console
The console appears as a tool window every time you choose the corresponding command on the Tools menu. You can assign a shortcut to open Python console: press Control+Alt+S , navigate to Keymap , specify a shortcut for Main menu | Tools | Python or Debug Console .
The main reason for using the Python console within PyCharm is to benefit from the main IDE features, such as code completion, code analysis, and quick fixes.
You can use up and down arrow keys to browse through the history of executed commands, and repeat the desired ones. To preview the variable values calculated in the course of the execution, click and check the Special Variables list.
The console is available for all types of Python interpreters and virtual environments, both local and remote.
Preview a variable as an array
When your variables are numpy arrays or dataframes, you can preview them as an array in a separate window. To try it, do one of the following:
- Click the link View as Array / View as DataFrame :
- From the context menu of a variable, choose View as Array / View as DataFrame :
The variable will be opened in the Data tab of the SciView window.
Run source code from the editor in console
- Open file in the editor, and select a fragment of code to be executed.
- From the context menu of the selection, choose Execute Selection in Python Console , or press Alt+Shift+E : With no selection, the command changes to Execute line in console . Choose this command from the context menu, or press Alt+Shift+E . The line at caret loads into the Python console, and runs.
- Watch the code selection execution:
By default, the Python console executes Python commands using the Python interpreter defined for the project. However, you can assign an alternative Python interpreter.
Run asyncio coroutines
- In the editor, select a fragment of code which contains the definition of an asyncio coroutine.
- From the context menu, select Execute Selection in Python Console , or press Alt+Shift+E :
- After the code is executed on the Python console, run the coroutine by using the await keyword:
Configure Python console settings
- In the Settings dialog ( Control+Alt+S ), select Build, Execution, Deployment | Console | Python Console .
- Select any available interpreter from the Python interpreter list. Note that you cannot introduce a new interpreter here. If you want to come up with the new interpreter, you need to create it first.
- In needed, click the Configure Interpreters link to inspect the list of the installed packages and add new ones. Mind the code in the Starting script area. It contains the script that will be executed after you open the Python console. Use it to pre-code some required Python commands.
When working on several Python scripts, you might want to execute each in a separate Python console.
Run several Python consoles
- Click to add a new Python console.
- By default, each console has the name Python Console with an index. To make a console reflect the script you’re running, right-click the console tab, select Rename Console , and enter any meaningful name.
All the commands you’re running in the Python console are executed one by one. If the commands require substantial time to get executed, you might want to preview and manage the execution queue.
Manage the command execution queue
- Go to Settings | Build, Execution, Deployment | Console and enable the Command queue for Python Console checkbox.
- Click on the console toolbar to open the queue.
- In the Python Console Command Queue dialog, review the list of commands. If needed, click to delete the command from the queue.
Note, once the command is executed, it disappears from the queue. To preview all previously executed commands browse the console history ().
Console tab
This tab is marked with and shows the output and error stream messages.
Console toolbar
Click this button to navigate up or down in the stack trace and have the cursor jump to the corresponding location in the source code.
Click this button to toggle the soft wrap mode of the output.
Click this button to navigate to the bottom of the stack trace and have the cursor jump to the corresponding location in the source code.
Click this button to send the console text to the default printer.
Click this button to remove all text from the console. This function is also available from the context menu of the console.
This button is available in the Debug console. If it is pressed, you can enter commands in the console and view output.
Note that in the debug console, code completion is available:
It’s also possible to scroll through the history of commands with the up and down arrow keys.
Press this button to show the Debug Console History dialog, where one can view the console entries and navigate through them, using the arrow keys.
Click OK to close the dialog.
Context menu options
Opens the Clipboard vs Editor dialog that allows you to view the differences between the selection from the editor and the current clipboard content. This dialog is a regular comparing tool that enables you to copy the line at caret to the clipboard, find text, navigate between differences and manage white spaces.
Choose this command to copy the current URL to the system clipboard. This command only shows on a URL, if it is included in an application’s output.
Choose this command to open the Create Gist dialog.
Keyboard shortcuts
The Control+D key combination allows you to send EOF (end of file), that is to signal that no more data can be read from a data source.