您可以通过以下方式自己动手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,请尝试一下。