PyCharm 2024.1 Help

Code Running Assistance

Prerequisites

  • You have already created a Python project and populated it with the following code:

    import math def demo(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__': a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) result = demo(a, b, c) print(result)
  • You have Python interpreter already configured. Note that for the current project your Python interpreter version should be 3.0 or later.

First run

Open the class Solver.py for editing F4, and right-click the editor background. Then choose Run 'Solver' from the context menu:

Run command

The script runs. Enter values for a, b, and c to review the output in the Run tool window:

Execution results

Let's explore in detail what we've done and what we see.

Run/debug configuration - what is it?

Each script or test you wish to run or debug from within PyCharm, needs a special profile that specifies the script name, working directory, and other important data required for running or debugging. PyCharm comes with a number of such pre-defined profiles, or run/debug configurations, that serve patterns, against which you can create any number of run/debug configurations of your own.

Every time you click Run Run or Debug Debug (or choose Run or Debug from the context menu), you actually launch the current run/debug configuration in the run or debug mode.

If you look at the very first image, you will notice that in the combobox there is no run/debug configuration at all; on the second image it appears, marked with the green circle. It means that the Solver run/debug configuration has been created automatically by PyCharm, when you've chosen Run 'Solver' from the context menu. Now, as this run/debug configuration is marked with the green circle, it is current.

Look at the Run widget on the image: you see that solver is selected as the current run/debug configuration. To the right of it, you see the Run Run and Debug Debug buttons.

You also see that its icon is shown semi-transparent. What does it mean? It means that the Solver run/debug configuration is temporary - PyCharm has created it automatically.

Now click Run/Debug configurations to see the available commands and the list of existing run/debug configurations:

List of the run/debug configurations

Should you have more run/debug configurations, the list of existing ones will become broader. If you click one of the run/debug configurations in this list, it will become current.

Save run/debug configuration

Click More Actions More Actions to see additional running options, including Run with Coverage, Profile, Start the concurrency visualization session. Below, there are available actions for the current configuration.

Additional command in the Run widget

Select Save Configuration - now this configuration becomes permanent and gets the normal icon.

Edit run/debug configuration

Now click Run/Debug configurations near solver and select Edit configurations. The Run/Debug Configurations dialog opens:

Run/debug configuration

Here you can see the solver configuration and its default settings.

The default configuration options are derived from the predefined Python template. Click the Edit configuration templates link, to preview and modify the patterns.

Modifying the configuration template

For example, here you change the default Python interpreter. Then it will ibe preselected in any newly created run/debug configuration of the Python type.

Let's go back to the Run/Debug Configurations dialog.

Under the Python node on the left, you see the only run/debug configuration solver. It is denoted with the icon of the normal opacity – which corresponds to the permanent run/debug configuration (remember, it became permanent because you've saved it – however, any specially created run/debug configuration also becomes permanent).

If you change anything in one of the existing run/debug configurations, then only this particular run/debug configuration will be affected.

Redirect standard input from a text file

You can use the Run/Debug Configuration dialog to automatically submit input values from a text file instead of typing them in the Run tool window.

  1. Create the in.txt file in the project root with the following values of a, b, and c:

    1 11 1
  2. Click the Run widget and select Edit Configurations. If you have several run configurations, select solver on the left.

  3. Click Modify options and select the Redirect input from. The corresponding field appears in the dialog.

    Specify the path to the in.txt file in it.

    Redirecting data from a text file to the standard input

Click Run at the bottom of the dialog to save the configuration and run it.

Redirecting data from a text file in standard input

Pass parameters to the running script

When running your Python scripts, you can pass various values as command-line arguments. Use the Parameter field in the Python run/debug configuration to add a parameter or to insert a macro.

  1. Modify the code sample so that it can use a command-line argument value instead of "4" in the calculations.

    import math import sys def demo(a, b, c): n = float(sys.argv[1]) d = b ** 2 - n * 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__': a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) result = demo(a, b, c) print(result)
  2. Click the Run widget and select Edit Configurations. If you have several run configurations, select solver on the left.

  3. Click Insert Macros Insert Macros in the Script parameters field and select ClipboadContent from the list of the available macros.

    Adding macros to the Solver run/debug configuration

    In this example, the clipboard contains the value 76, and that is shown in the Macro preview area.

    Click Insert to add the selected macro.

  4. Run the Solver run/debug configuration. Note that the command line now contains "76" as an argument.

    Executing Solver with the clipboard content as a command-line argument
  5. Copy any numeric value into the clipboard and rerun the configuration to evaluate the macro.

  6. When you are ready, rollback the modifications you've made to the script, as we won't need them in the following tutorials.

Similarly, you can include other helpful macros:

  • $FilePath$: for the file path of the open file

  • $ModuleSdkPath$: for the project interpreter path

  • $Prompt$: for a string input dialog on running the configuration

Regular run

You've already executed the solver script in one of the most straight-forward ways. Let's now explore the other ways to run a script.

  1. Make sure that 'solver' run/debug configuration is the current one in the Run widget.

  2. Do one of the following:

    • Click the Run button Run, located next to the run/debug configuration combobox.

    • Press Shift+F10.

    • Go to Run | Run.

Now you can observe results in the Run tool window.

Test run

We won't discuss here why testing is necessary – let's assume that it is so, and discuss how PyCharm can help with it.

Creating a test

To run a test, you have to create it first. PyCharm suggests a smart way to stub a test out: click the class name and then press Ctrl+Shift+T, or go to Navigate | Test in the main menu. If a test exists, you can jump directly to it; if it doesn't, PyCharm will create it:

Create a test

Click the suggested action, and PyCharm will show the following dialog:

Test dialog

Click OK, and see the test class is opened in the editor:

Auto generated test

PyCharm has produced a test class for us. However, this is just a stub which lacks the actual testing functionality. So, we will import the class to be tested, and add a test method. The resulting code might be as follows:

import unittest from Solver import Solver class MyTestCase(unittest.TestCase): def test_negative_discr(self): s = Solver() self.assertRaises(Exception) def test_something(self): self.assertEqual(True, False) if __name__ == '__main__': unittest.main()

Running a test

When ready with the testing code, right-click the test class name and select Run Python tests.

Running a test from the context menu

Launch it and observe results in the Test Runner tab of the Run tool window. To see successful test along with the failed ones, click Show Passed Show Passed on the toolbar.

Test run

Debug run

First of all, why do we need debugging? Suppose, you hit a runtime error. Sometimes the reason of the error is clear. But in more complex case you may need to investigate and inspect the state of your program at different points in its execution. This is where debugging is necessary.

With PyCharm, you can debug your applications without leaving the IDE. The only thing you need to do beforehand is to place breakpoints in the required places. Let's explore this in details.

Breakpoint - what is it?

A breakpoint is a line of the source code, where PyCharm will suspend, when this line is reached. PyCharm discerns several types of breakpoints, each one denoted with its own icon.

Setting breakpoints

This is definitely the easiest part of the process. Just click the gutter on the lines you want to explore – and the breakpoints are there:

Breakpoints

Note that each breakpoint is denoted also with a red stripe over the entire line. This color corresponds to a breakpoint that has not yet been reached. Later we will see how the line at breakpoint changes its color.

By the way, removing breakpoints is same easy – click the gutter.

Hover over a breakpoint. PyCharm shows a tooltip with the most essential breakpoint information – line number and script address. However, if you want to change breakpoint settings, you have to right-click a breakpoint. Try changing breakpoint settings for your own, and see how the breakpoint icon changes.

Debugging session

So, we are now ready for debugging. Let's start.

First of all, select the solver run/debug configuration in the Run widget and click Debug.

What happens next?

  • PyCharm starts, and then suspends execution at the first breakpoint.

  • The line at breakpoint becomes blue. It means that PyCharm has reached the line with the breakpoint, but has not yet executed it.

  • Next to the executed lines in the editor, the values of the variables appear.

  • The Debug tool window appears. This tool window shows all the important information related to debugging, and allows managing the debugging process.

Debug the script

For more information, refer to the product documentation.

Working in the Threads and Variables tab

OK, we've paused at the first breakpoint. What's next?

Press F9 or click Resume. The program will resume and pause at the next breakpoint. This way you can step through all the set breakpoints, observing the variables used in the application. For more information, refer to Debug.

Working in the Console tab

Why do we need it at all? For example, you'd like to see the error messages, or perform some calculations not related to the current application... With PyCharm this is not a problem.

Click the Console tab to bring it forward.

Try to execute Python commands in this interactive console:

Interactive debugging console

Note that interactive console provides code completion Ctrl+Space and history (Up/Down arrow keys). For more information, refer to the page Using Debug Console.

You can always invoke the debug console by using the command Tools | Open Debug Command Line from the main menu.

For more information on the Debug tool window, refer to the section Debugger tab.

REPL - Running in the Python console

Finally, if you are used to working with an Python console, you can also do that right from within PyCharm. To launch the console, select Run File in Python Console from the context menu.

You can handle the script execution in the interactive mode:

Running in the Python console

For more information, refer to Python console.

Last modified: 05 July 2024