Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pdb Python code with input?

Tags:

python

I'm debugging Python code with pdb. The code need input from stdin, like:

python -m pdb foo.py < bar.in

Then the pdb will accept the bar.in as commands. How to tell pdb that the input is for foo.py and not for pdb?

like image 954
Stephen Hsu Avatar asked May 04 '10 09:05

Stephen Hsu


People also ask

How do I use pdb code in Python?

Starting Python Debugger To start debugging within the program just insert import pdb, pdb. set_trace() commands. Run your script normally, and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace().

How do I display a variable in pdb?

pdb is a fully featured python shell, so you can execute arbitrary commands. locals() and globals() will display all the variables in scope with their values. You can use dir() if you're not interested in the values.

What is PBD in Python?

Pdb is a powerful tool for finding syntax errors, spelling mistakes, missing code, and other issues in your Python code.


2 Answers

Well, this is a tweak to Aaron's answer, but I think it misses the point in that you want to interactively debug at some point, right? This works but the program exits before you get a chance to debug.

(echo cont;cat bar.in) | python -m pdb foo.py

I think if you can edit foo.py, do import pdb then at the interesting point in foo.py do pdb.set_trace(), and just run python foo.py without the -m pdb and give it bar.in normally

python foo.py < bar.in
like image 145
Peter Lyons Avatar answered Oct 20 '22 05:10

Peter Lyons


A kind of gross work around is to put cont at the beginning of bar.in:

cont
one
two
three
four


aaron@ares ~$ python -m pdb cat.py < bar.in 
> ~/cat.py(1)<module>()
-> import sys
(Pdb) one
two
three
four
The program finished and will be restarted
> ~/cat.py(1)<module>()
-> import sys
(Pdb) 
like image 28
Aaron Maenpaa Avatar answered Oct 20 '22 04:10

Aaron Maenpaa