我正在 python 调试器 (pdb) 上编写一个简单的包装器,我需要解析 pdb 输出。但我在从过程管道读取文本时遇到问题。
我的代码示例:
import subprocess, threading, time
def readProcessOutput(process):
while not process.poll():
print(process.stdout.readline())
process = subprocess.Popen('python -m pdb script.py', shell=True, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
read_thread = threading.Thread(target=readProcessOutput, args=(process,))
read_thread.start()
while True:
time.sleep(0.5)
当我在 OS shell 中执行给定命令(python -m pdb script.py)时,我得到如下结果:
> c:\develop\script.py(1)<module>()
-> print('hello, world!')
(Pdb)
但是当我运行脚本时,我只得到两行,但无法得到 pdb 提示。此后向 stdin 写入命令无效。所以我的问题是: 为什么我看不懂第三行?如何避免这个问题并获得正确的输出?
平台:Windows XP、Python 3.3
最佳答案
第三行无法被 readline()
读取,因为它尚未在行尾终止。您通常会在“(pdb)”后面看到光标,直到您输入任何内容并输入。
与有一些提示的进程的通信通常更复杂。事实证明,首先要为数据写入器编写一个独立的线程,以便更轻松地测试通信,以确保如果尝试写入或读取太多数据,主线程永远不会卡住。然后就可以再简化一下。
关于python - 读取进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895526/