您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python实时编码/调试

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,请尝试一下。

python 2022/1/1 18:50:19 有374人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶