Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a new function in pdb

Why can't I define new functions when I run pdb?

For example take myscript.py:

#!/gpfs0/export/opt/anaconda-2.3.0/bin/python
print "Hello World"
print "I see you"

If I run python -m pdb myscript.py and try to interactively define a new function:

def foo():

I get the error:

*** SyntaxError: unexpected EOF while parsing (<stdin>, line 1)

Why is this?

like image 815
irritable_phd_syndrome Avatar asked Mar 07 '16 19:03

irritable_phd_syndrome


People also ask

How to add a breakpoint in pdb?

Just use python -m pdb <your_script>. py then b <line_number> to set the breakpoint at chosen line number (no function parentheses). Hit c to continue to your breakpoint. You can see all your breakpoints using b command by itself.

How do you step out in pdb?

As mentioned by Arthur in a comment, you can use r(eturn) to run execution to the end of the current function and then stop, which almost steps out of the current function. Then enter n(ext) once to complete the step out, returning to the caller.

How does pdb work?

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame.


3 Answers

I don't think it supports multi-line input. You can workaround by spawning up an interactive session from within pdb. Once you are done in the interactive session, exit it with Ctrl+D.

>>> import pdb
>>> pdb.set_trace()
(Pdb) !import code; code.interact(local=vars())
(InteractiveConsole)
In : def foo():
...:     print('hello in pdb')
...: 
In : # use ctrl+d here to return to pdb shell...
(Pdb) foo()
hello in pdb
like image 145
wim Avatar answered Oct 14 '22 21:10

wim


You can define your function in a one line statement using ; instead of indentation, like this:

(Pdb) def foo(): print 'Hello world'; print 'I see you'
(Pdb) foo()
Hello world
I see you
like image 27
Forge Avatar answered Oct 14 '22 20:10

Forge


i was able to import python modules from the pdb command line.

if you can import python modules, then you should be able to define your functions in a file and just do an import of the file.

like image 22
Trevor Boyd Smith Avatar answered Oct 14 '22 20:10

Trevor Boyd Smith