交互式调试来自另一个程序的 python 代码

Debug Interactively a python code from another program

我正在编写一个 python 支持调试的编辑器。我必须像 IDE 一样从我的应用程序中 交互地 调试一个 python 代码,但没有很多选项。

我知道 bdb 和 pdb,但我必须执行保存到文件中的脚本并发送 step over、continue、quit 等命令[= =14=]

我正在尝试将 subprocess lib 与 pdb 结合使用,但没有取得好的结果。

p = subprocess.Popen(args=[sys.executable, '-m', 'pdb', 'mide.py'],
                 stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 universal_newlines=True)
p.communicate('s')
p.communicate('s')# I know why this line doesn't work, it's just a example how i wanted to do it.

如何在 python 3.x 中使用它?我只需要一条路可走,但最好只使用 python 3 没有外部依赖。

P.S。我正在使用 PyQt5。

来自 communicate 上的子流程文档:

Popen.communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

因此,当调用 communicate 时,它将等待进程终止。无法调用第二次,因为进程已经终止。

您或许应该自己直接阅读 stdoutstderr。这必须在不同的线程中完成,或者您必须不时轮询一次以查看数据是否可用。 pdb 执行每条命令可能需要一段未知的时间,因此您不知道输出何时准备就绪。您通过写入进程 stdin.

来发送命令

您可能还想查看 pexpect 模块 here。但是它还没有很好的 Windows 支持。