Pdb / Debug Python Script Interactively
Debug Python Script Interactively
Debugs a specified Python script interactively using pdb.
python -m pdb <path/to/file.py> python -m pdb <path/to/file.py> #!/bin/bash
# Debug Python Script Interactively
python -m pdb {{path/to/file.py}} import subprocess
# Debug Python Script Interactively
# Make sure to replace <placeholders> with actual values
def run_command():
cmd = [
"pdb",
"-m",
"pdb",
"<path/to/file.py>"
]
try:
print(f"Executing: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
except FileNotFoundError:
print("Error: pdb not found. Please install it first.")
if __name__ == "__main__":
run_command() When To Use
When needing to analyze and fix bugs in scripts during development.
Pro Tip
Set breakpoints within the code for targeted debugging before execution starts.
Anatomy of Output
Understanding the result
> path/to/file.py(10)<module>() Current Frame Indicates the current line of execution.
(Pdb) list Debugger Command Shows the surrounding code.
(Pdb) continue Debugger Command Resumes execution until the next breakpoint.
Troubleshooting
Common pitfalls
FileNotFoundError: [Errno 2] No such file or directory: 'path/to/file.py'
Solution: Verify the script file path.
ImportError: cannot import name 'nonexistent'
Solution: Check for correct module and function names.
AttributeError: 'NoneType' object has no attribute 'method'
Solution: Investigate potential None returns from previous function calls.
Command Breakdown
What each part is doing
-
python - Base Command
- The executable that performs this operation. Here it runs Pdb before the shell applies any redirect operators.
-
<path/to/file.py> - Input Files
- The file path or paths supplied to this command.
-
-m - Command Option
- Tool-specific option used by this command invocation.
Alternative Approaches
Comparable commands in other tools
Alternative programming tools for the same job.
pypy -m pdb <path/to/file.py> Exercism / Download Exercise Hello World exercism download --track <programming_language> --exercise hello-world Nextflow / Run Pipeline With Specific Work Directory And Report nextflow run <workflow> -work-dir <path/to/directory> -with-report <report.html> Nodenv / List Available Node Versions nodenv install --list Perl / Say First Match Group Ignore Space perl -n -E 'say $1 if m/<before> ( <group_regex> ) <after>/x'