gpt4 book ai didi

Python实时编码/调试

转载 作者:太空狗 更新时间:2023-10-29 19:25:33 35 4
gpt4 key购买 nike

有没有办法在程序执行期间生成一个交互式 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())

我还没有测试过它,但如果您的程序不连续将内容打印到控制台,这可能没问题 - 否则它会与交互式解释器一起处理。 p>

“打开一个新控制台”的想法很有趣,但非常特定于环境,所以我不会解决这个问题。如果有更好的预打包解决方案,我会很感兴趣。

编辑:尝试多处理解决方案:

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 传递给子进程,事情从那里变得有点棘手。 注意 在 python 3.2 和更低版本中存在一个错误,当您在 multiprocessing 进程中调用 exit() 时,它会导致回溯喷发。这在 3.3 中已修复。

不幸的是,multiprocessing 代码只能在 POSIX 兼容系统上运行 - 即不能在 Windows 上运行。并非不可逾越,只是需要涉及管道的更复杂的解决方案。

无论如何,如果您在主线程中接近 100% 的 CPU 使用率,多处理 实现可能会为您执行得更好。如果您使用的是 *nix,请尝试一下。

关于Python实时编码/调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757232/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com