17

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?

Forge
  • 6,538
  • 6
  • 44
  • 64
irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60

4 Answers4

26

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
wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    Since Python 3.2, there's the pdb builtin command `interact` that does this. https://docs.python.org/3/library/pdb.html#pdbcommand-interact – KFL Aug 31 '21 at 17:50
  • @KFL Thanks for the comment, but how would you make a function defined in there remain visible after exiting interaction? The InteractiveConsole spawned by pdb builtin `interact` does seems to contain names from the outer scope, but any functions defined within don't seem to be usable after exiting the interaction. – wim Aug 31 '21 at 18:09
8

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
Forge
  • 6,538
  • 6
  • 44
  • 64
1

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.

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
1

If your application happens to have IPython as a dependency, you could drop yourself into a feature-rich IPython REPL right from ipdb:

import IPython; IPython.embed()

From inside, if you run IPython's magic command whos, you should see all the locally defined variables in the current pdb frame.

KFL
  • 17,162
  • 17
  • 65
  • 89