start interactive mode on a specific script line

2019-03-15 08:45发布

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?

4条回答
一纸荒年 Trace。
2楼-- · 2019-03-15 09:21

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.

查看更多
戒情不戒烟
3楼-- · 2019-03-15 09:27

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

查看更多
劫难
4楼-- · 2019-03-15 09:33

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

查看更多
【Aperson】
5楼-- · 2019-03-15 09:40

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.

查看更多
登录 后发表回答