pycharm отладка кода python
Debug
There is a variety of ways how you can run a debugging session, however, for simplicity this documentation assumes that you are building and running your project from PyCharm. This is the most common case, and it has fewer limitations as compared to more advanced techniques. The procedures for attaching to a process and debugging a remote application are covered in separate sections.
Configure debugging options
If you are new to debugging, the out-of-the-box configuration will work for you. The topics about each debugger functionality provide references and explain the related settings where applicable. If you are an advanced user and looking for some particular property, see the Debugger reference section.
Under the Build, Execution and Deployment section, select Python Debugger, and configure the Python debugger options.
Under the Project | Python Interpreter section, configure the Python packages that might be required for some debugging configurations.
Define a run/debug configuration if you are going to use a custom one. This is required if you need some arguments to be passed to the program or some special activity to be performed before launch. For more information on how to set up run/debug configurations, refer to the Run/debug configurations section. Most of the time, you don’t need this to debug a simple program that doesn’t expect arguments or have any special requirements.
General debugging procedure
There is no one-size-fits-all procedure for debugging applications. Depending on actual requirements you may have to use different actions in different order. This topic provides general guidelines, which represent typical debugging steps. The details on how and when to use particular features are provided in the respective topics.
The alternative to using breakpoints is manually suspending the program at an arbitrary moment, however this method imposes some limitations on the debugger functionality and doesn’t allow for much precision as to when to suspend the program.
Just right-click any line in the editor and select the Debug command from the context menu.
After the program has been suspended, use the debugger to get the information about the state of the program and how it changes during running.
The debugger provides you with the information about variable values, the current state of the threads, breakdown of objects that are currently in the heap, and so on. It also allows you to test your program in various conditions by throwing exceptions (for example, to check how they are handled) or running arbitrary code right in the middle of the program execution.
While these tools let you examine the program state at a particular instant, the stepping feature gives you the control over step-by-step execution of the program. By combining the tools you can deduce where the bug is coming from and test your program for robustness.
Step 2. Debug your first Python application
Finding out the origin of the problem
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 our average speed:
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
PyCharm starts a debugging session and shows the Debug tool window
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:
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 Ctrl+Alt+T ( Code | Surround with ):
PyCharm creates a stub if construct, leaving you with the task of filling it with the proper contents.
After editing, we get the following:
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.
We can use the stepping toolbar buttons to choose on which line we’d like to stop next.
Watching
At first, you see the time equals nil- 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:
See Watches section for details.
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:
Evaluating expressions
Then in the dialog that opens, click Evaluate :
Actually, you could see the same thing with a watch. With evaluate expression you can do things that you can’t do with a watch: you can change things.
For example, if you enter the desired value of the odometer, say, 50, and then continue stepping through your script, you will get the following:
See the Evaluate expressions section for details.
Summary
So, you’ve done it! Congrats! Let’s repeat what you’ve done with the help of PyCharm:
Remote Debugging with PyCharm
With PyCharm you can debug your application using an interpreter that is located on the other computer, for example, on a web server or dedicated test machine.
PyCharm provides two ways to debug remotely:
Case: Use this approach to leverage extended debugging capabilities available on the remote machine.
Requirements: SSH access from the local machine to the remote server.
Case: Use this approach to integrate the debugging process into the series of running processes on the remote server. This might be helpful when you cannot explicitly run your application for debugging, or when some preparations tasks are required.
Requirements: SSH access from the local machine to the remote server, access from the remote server to the local machine using any predefined port.
Before you start
Complete the following preparation tasks:
On the local machine, create a pure Python project, as described in the section Create a Python project.
Add the following code to the Python File :
Creating a deployment configuration for a remote interpreter
Configure a remote interpreter
Ensure that you have SSH access to the remote machine.
Add a new remote interpreter to the project as described in Configure an interpreter using SSH specifying the credentials to connect to the remote machine.
Once you create the remote interpreter for your project, the corresponding deployment configuration is created. To preview it, click Ctrl+Alt+S to open the Settings dialog window on the local machine, then click the Build, Execution, Deployment node and the Deployment node.
You can accept all default settings or alter them, if needed. For this example, let’s use a meaningful name for your deployment configuration, for example, «MySFTPConnection».
Ensure that the Root path value reflects the path specified in the corresponding settings of the created SSH interpreter.
Now your deployment configuration is ready.
Deploy your application to a remote host
Next, your application must be deployed to the remote host.
File Transfer tool window appears. Verify the number of transferred files.
Debug your application
Right-click the editor background and choose the Debug (here Debug ‘quadratic_equation’ ).
Review the debugging output. Note that debugging actually takes place on the specified remote server.
Remote debugging with the Python remote debug server configuration
You can also enable remote debugging with the dedicated run/debug configuration, namely, Run/Debug Configuration: Python Debug.
Create a run/debug configuration
Map the path on the local machine to the path on the remote machine:
Inspect the Update your script instructions. You can use the pydevd-pycharm.egg from the PyCharm installation (
/debug-egg/pydevd-pycharm.egg ) or install the pydevd-pycharm package using pip.
Depending on your choice, perform the following changes:
Install the pydevd-pycharm package on the remote machine by running the following command:
pip install pydevd-pycharm
for example, pip install pydevd-pycharm
Modify the source code file as follows:
Modify the code as follows:
Create a SFTP connection
On the remote machine, create a directory where the file quadratic_equation.py should be uploaded. You can do it in the Terminal window:
In the Connection tab, specify the SFTP host (address of the remote machine), username and password for that machine.
Note that the specified user should have SSH access to the remote host.
Deploy files to the remote machine
Inspect the File Transfer dialog window to ensure that the files from the local machine are uploaded to the remote server.
Launch the Debug Server
Ensure that the Debug tool window shows the Waiting for process connection.. message. This message will be shown until you launch your script on the remote machine, and this script will connect to the Debug Server.
Execute the Python file on the remote machine
On the remote machine, navigate to the tmp/pycharm_project_986 directory.
Launch the quadratic_equation.py file on the remote host. To do that, in the Terminal window, enter the following command:
The most helpful aspect of this debugging method is that you can run execution the Python file using any of your bash scripts when remote debugging is part of a scheduled task or when you need to execute some preparation steps before running the Python script. If that’s the case, add the following lines to the appropriate place of your bash script:
Debug your application
On your local machine, switch to the Debug tool window. It should show the connection to the pydev debugger.
Your code is actually executed on the remote host, but debugged on the local machine.
Summary
In order to debug with a remote interpreter, you have to start your program through PyCharm, which is not always possible. On the other hand, when using the Debug Server, you can connect to a running process.
Run/Debug Configuration: Python
When you run your application for the very first time, PyCharm automatically creates the temporary Run/Debug configuration. You can modify it to specify or alter the default parameters and save it as a permanent Run/Debug configuration.
Prerequisites
Refer to their respective download and installation pages for details:
Configuration tab
Item | Description | |||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Script path/Module name | Click the list to select a type of target to run. Then, in the corresponding field, specify the path to the Python script or the module name to be executed. | |||||||||||||||||||||||||||||||||||||||||||
Parameters | ||||||||||||||||||||||||||||||||||||||||||||
Run with Python console | Enables running your script or module with the Python console. | |||||||||||||||||||||||||||||||||||||||||||
Redirect input from | Enables redirecting data from a text file to standard input. Use this option if your script requires some input and you want to automatically submit the values instead of typing them in the Run console. To enable redirecting, select the checkbox and specify the path to the target text file. | |||||||||||||||||||||||||||||||||||||||||||
Docker container settings This field only appears when a Docker-based remote interpreter is selected for a project.. Run options : Use this field to specify the Docker command-line options. This field only appears when a Docker Compose-based remote interpreter is selected. You can use the following commands of the Docker Compose Command-Line Interface: You can expand this field to preview the complete command string. Example: if you enter the following combination in the Commands and options field: the preview output should looks as follows: Logs tabUse this tab to specify which log files generated while running or debugging should be displayed in the console, that is, on the dedicated tabs of the Run or Debug tool window.
Common settingsWhen you edit a run configuration (but not a run configuration template), you can specify the following options: Select to allow running multiple instances of this run configuration in parallel. By default, it is disabled, and when you start this configuration while another instance is still running, PyCharm suggests to stop the running instance and start another one. This is helpful when a run/debug configuration consumes a lot of resources and there is no good reason to run multiple instances. ToolbarThe tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.
Before launchIn this area, you can specify tasks to be performed before starting the selected run/debug configuration. The tasks are performed in the order they appear in the list.
|