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?

2
  • If debug mode is what I described above, then yes! Aug 3, 2012 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 3, 2012 at 13:25

4 Answers 4

23

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

3
  • 1
    Are you sure? It only looks like it opens a python shell, and that's it. I can't lookup any variables that I defined before code.interact() in my code, so I don't really see how to use this function. Aug 3, 2012 at 13:25
  • 11
    @Ricky You must use the local argument: code.interact(local=locals()). Aug 3, 2012 at 13:26
  • With autocomplete features too: stackoverflow.com/a/50918009/1045199 Oct 27, 2022 at 20:29
10

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.

0
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.