[파이썬] pdb `step` 또는 `s` 명령어 활용

Python Debugger Logo

When debugging Python code, it is often necessary to step through the code line by line to understand the flow and identify any issues. The Python Debugger (PDB) provides various commands to help you navigate through your code, and two of the most commonly used commands are step and s.

The step Command

The step command, usually abbreviated as s, allows you to execute the current line of code and then move to the next line. If the current line contains a function call, it will enter that function and pause at the first line of the function.

Here’s an example of how to use the step command in PDB:

import pdb

def foo():
    x = 1
    y = 2
    z = x + y
    return z

def bar():
    a = 3
    b = 4
    c = foo() + a + b
    return c

pdb.set_trace()
result = bar()
print(result)
  1. In this example, we have two functions foo and bar. We set a trace using pdb.set_trace() to start the debugger at that point.
  2. When we run the code and reach the breakpoint, the debugger will prompt us with a (Pdb) prompt.
  3. Type s or step and press Enter to execute the current line of code and move to the next line.
  4. The debugger will now pause at the first line of the foo function. We can continue stepping through the code line by line until the end of the program.

The s Command

The s command is simply a shorter alias for the step command. You can use either of these commands interchangeably. So, instead of typing step, you can type s.

Example:

(Pdb) s
> /path/to/file.py(4)foo()
-> x = 1
(Pdb) s
> /path/to/file.py(5)foo()
-> y = 2

Conclusion

In this blog post, we explored how to use the PDB step and s commands to step through your Python code during debugging. These commands allow you to execute the current line and move to the next line, providing valuable insights into the flow of your program. Whether you prefer to use step or s, both commands serve the same purpose and can help you identify and resolve issues in your code more effectively.