My Python script is crashing. To debug it, I ran it in interactive mode python -i example.py
Traceback (most recent call last):
File "example.py", line 5, in <module>
main()
File "example.py", line 3, in main
message[20]
IndexError: string index out of range
At this point, I would like to inspect the variable message
. I tried
>>> message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'message' is not defined
Alas message
is not in scope (though main
is). That's frustrating. How can I inspect the variable? Is there a more useful version of python -i
that keeps what's in scope at the crash (rather than the top level)?
Code used for example.py
above. Needless to say, this is a simplification.
def main():
message = "hello world"
message[20]
main()
According to the Python docs https://docs.python.org/3.4/library/pdb.html
pdb.py
can also be invoked as a script to debug other scripts. For example:python -m pdb myscript.py
. When invoked as a script, pdb will automatically enter post-mortem debugging if the program being debugged exits abnormally.
This isn't entirely accurate. It actually enters debugging at the first line.
$ python -m pdb example.py
> example.py(1)<module>()
-> def main():
However if you type c
it will then continue to the crash
(Pdb) c
Traceback (most recent call last):
File "C:\Python34\lib\pdb.py", line 1661, in main
pdb._runscript(mainpyfile)
File "C:\Python34\lib\pdb.py", line 1542, in _runscript
self.run(statement)
File "C:\Python34\lib\bdb.py", line 431, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "example.py", line 1, in <module>
def main():
File "example.py", line 3, in main
message[20]
IndexError: string index out of range
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> example.py(3)main()
At this point you can type message
to inspect the variable.
-> message[20]
(Pdb) message
'hello world'
Wahey!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments