13

I need to run my Python script as usual, but I want to stop execution on a specific line and start interactive mode.

In other words, I want to be able to check the value of all my variables at that point, and continue myself from there on python's command line.

How can I do this?

msw
  • 42,753
  • 9
  • 87
  • 112
Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185
  • If debug mode is what I described above, then yes! – Ricky Robinson Aug 03 '12 at 13:19
  • As long as you are trying to debug your code, the methods in the answers are the way you should go. If you actually need this sort of functionality as a user rather than as a developer of your script, you should be looking at ways to take user input during script execution or reorganizing your code in to functions, methods, and modules. – Silas Ray Aug 03 '12 at 13:25

4 Answers4

23

This can be done with the code module. The easiest way is to call code.interact().

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
9

Use a debugger and add breakpoints. Do you use an IDE? All the major IDEs have debugger support. From the CLI, you can use pdb.

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
5

Not exactly what you're looking for, but you can easily have your program break out to pdb (the Python debugger) by adding this line wherever you want your program to break out:

import pdb; pdb.set_trace()

You can then easily check variables like this:

p variable_name

You can also step, continue etc.

More detail on pdb here.

Dave Cahill
  • 448
  • 2
  • 15
2

Unless you need this for production purposes the best way, in my opinion, is to use interactive debugger:

http://infohost.nmt.edu/tcc/help/pubs/python/web/pdb.html

http://onlamp.com/pub/a/python/2005/09/01/debugger.html

for other purposes consider maybe doing aspects on your code, using decorators to get runtime characteristics from method class:

http://www.cs.tut.fi/~ask/aspects/index.shtml

http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch26.html

Edmon
  • 4,752
  • 4
  • 32
  • 42