[파이썬] pdb `next` 또는 `n` 명령어로 코드 단계별 실행

When debugging a Python program, it is often helpful to execute the code line by line to understand its behavior and track down any errors. The pdb module in Python provides a powerful debugger that allows you to do just that.

One of the most commonly used commands in pdb is next or n. This command allows you to execute the current line of code in your program and move to the next line.

To use the next command in pdb, follow these steps:

  1. Import the pdb module in your Python script:
import pdb
  1. Set a breakpoint in your code at the line where you want the debugger to start:
pdb.set_trace()
  1. Run your program.

  2. Once the debugger is triggered and you are in the interactive mode, type n or next and press enter to execute the current line of code and move to the next line.

Here’s an example to demonstrate the usage of next command in pdb:

import pdb

def greet(name):
    pdb.set_trace()
    print(f"Hello, {name}!")

def main():
    name = input("Enter your name: ")
    greet(name)
    print("Program execution completed.")

if __name__ == "__main__":
    main()

Let’s say we want to debug the greet function. We set a breakpoint using pdb.set_trace() at the start of the greet function. When we run the program, it will stop at that line.

Once the debugger is triggered, we can use the n or next command to execute each line of code step by step.

For example, if we type n and press enter, it will execute print(f"Hello, {name}!") and move to the next line, which in this case is the next line after the function call in the main function.

Using the next command allows us to inspect the values of variables, check the flow of control, and analyze code behavior line by line, making it an invaluable tool for debugging Python programs.

Remember to remove all pdb related code (including the import pdb line and the pdb.set_trace() line) once you have finished debugging your program.

Happy debugging!