Python实时编码/调试
有没有一种方法可以在程序执行期间生成交互式python控制台(最好是iPython), 而不会暂停主程序,
并且能够检查和修改程序变量?与浏览器为JavaScript提供的功能类似。
我知道pdb.set_trace()
和IPython.embed()
,但是它们都暂停程序执行,并要求将它们放在程序的源代码中的某个位置。
这对于使用python开发桌面游戏非常有用。
-
您可以通过以下方式自己动手
threading
:#!/usr/bin/python3 def _spawn_background_interpreter(*args,**kwargs): from threading import Thread def _open_interp(locs): import code code.interact(local=locs) locs = args[0] if args else None t = Thread(target=_open_interp, args=(locs,)) t.setDaemon(True) #pre-3.3 API t.start()
致电
_spawn_background_interpreter(locals())
。我还没有测试过,但是如果您的程序不连续地将内容打印到控制台上,这 可能 会很好-否则它将与交互式解释器融合在一起。
“打开新控制台”的想法很有趣,但是非常针对特定环境,因此我不会解决。如果有更好的预包装解决方案,我将很感兴趣。
编辑: 尝试
multiprocessing
解决方案:def _spawn_background_interpreter(*args,**kwargs): from multiprocessing import Process import sys, os def _open_interp(locs,stdin): import code sys.stdin = os.fdopen(stdin) code.interact(local=locs) locs = args[0] if args else None fileno = sys.stdin.fileno() p = Process(target=_open_interp, args=(locs,fileno)) p.daemon = True p.start()
我最初避免的原因
multiprocessing
是每个新进程都有自己的PID(和stdin)。因此,我不得不将主线程的stdin传递给子进程,然后事情就变得有些棘手了。
请注意 ,在python
3.2及更低版本中存在一个错误,该错误将在您exit()
在multiprocessing
进程中调用的任何时间引起回溯。这在3.3中已修复。不幸的是,该
multiprocessing
代码仅在符合POSIX的系统上运行-
即不在Windows上运行。并非不可克服,只是需要涉及管道的更复杂的解决方案。无论如何,
multiprocessing
如果您的主线程中的CPU使用率接近100%,则实现可能会为您带来更好的性能。如果您使用* nix,请尝试一下。