随时随地在Python中翻译成口译 [英] Drop into an Interpreter anytime in Python
问题描述
我知道如何使用 pdb
和 IPython
下载到一个解释器,但这需要事先准确知道哪里我想停下来然而,我经常运行数字捣蛋脚本,需要几分钟到几个小时,我想知道它的进步是什么。一个解决方案是简单地将大量的日志记录语句放在任何地方,但是我或者淹没了太多的信息,或者无法正确记录我想知道的内容。
I know how to drop into an interpreter with pdb
and IPython
, but this requires me knowing beforehand exactly where I want to stop. However, I often run number crunching scripts that take minutes to hours, and I would like to know exactly what it's progress is. One solution is to simply put lots of logging statements everywhere, but then I either inundate myself with too much information or fail to log exactly what I want to know.
是否有一种初始化监听器循环的方法,在一些关键组合下,我会将代码放在当前的代码中?认为CTRL + Z,但让我在Python而不是Bash。
Is there a way to initialize a listener loop that under some key combination will drop me into the code wherever it currently is? Think CTRL+Z but leaving me in Python rather than Bash.
推荐答案
您可以使用信号模块来设置一个处理程序,当您击中control-C或control-Z或任何...时,将启动调试器。SIGINTR, SIGSUSP。
You can use the signal module to setup a handler that will launch the debugger when you hit control-C or control-Z or whatever.. SIGINTR, SIGSUSP.
例如,定义一个模块 instant_debug.py
,覆盖SIGQUIT,
For example, define a module instant_debug.py
that overrides SIGQUIT,
import signal
import pdb
def handler(signum, frame):
pdb.set_trace()
signal.signal(signal.SIGQUIT, handler)
然后make a脚本
import instant_debug
import time
for i in xrange(1000000):
print i
time.sleep(0.1)
在执行过程中,您可以通过键入 CTRL + \
跳转到代码中,使用 u
和 d
如正常 pdb
,然后继续 c
,好像没有发生任何事情。请注意,您只能在下一个原子操作结束时跳入 - 这意味着在一个巨大的C模块中间不会停止。
At any point during execution, you can jump into the code by typing CTRL+\
, examine the stack with u
and d
as in normal pdb
, then continue with c
as if nothing ever happened. Note that you will only jump in at the end of the next "atomic" operation -- that means no stopping in the middle of a giant C module.
这篇关于随时随地在Python中翻译成口译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!