python - 在 QPlainTextEdit 中使用 tqdm 显示终端输出

标签 python pyqt pyqt5 tqdm qplaintextedit

我正在尝试找到一种方法,与其他打印一起获取 pyqt 应用程序中进度条的结果/演变,例如在 QPlainTextEdit 小部件中。

我面临的问题是,进度条可以使用一些更高级的回车符,甚至更高级的光标定位,而这些大多不受treams支持。 我尝试过io.StringIO,但\r保持文字。

import io
from tqdm import tqdm
s = io.StringIO()
for i in tqdm(range(3), file=s):    
    sleep(.1)

输出:

s.getvalue()

Out[24]: '\n\r  0%|          | 0/3 [00:00<?, ?it/s]\x1b[A\n\r 33%|###3      | 1/3 [00:00<00:00,  9.99it/s]\x1b[A\n\r 67%|######6   | 2/3 [00:00<00:00,  9.98it/s]\x1b[A\n\r100%|##########| 3/3 [00:00<00:00,  9.98it/s]\x1b[A\n\x1b[A'

翻译成:

print(s.getvalue())
  0%|          | 0/3 [00:00<?, ?it/s]
 33%|###3      | 1/3 [00:00<00:00,  9.99it/s]
 67%|######6   | 2/3 [00:00<00:00,  9.98it/s]
100%|##########| 3/3 [00:00<00:00,  9.98it/s]

需要明确的是,在我的输出中,我不想每次 tqdm 更新一行,而只是当前状态,因为它将打印在命令行上。

知道如何做到这一点吗? 谢谢!

最佳答案

这个想法是,如果添加了新文本,则删除前一行,但您还必须删除 \r 并验证它不是空文本。另外,对于接收tqdm文本的对象,它必须只有write()方法,因此实现一个自定义的QPlainTextEdit。使用QMetaObject::invokeMethod()使其线程安全

import time
import threading
from tqdm import tqdm
from PyQt5 import QtCore, QtGui, QtWidgets
import lorem

class LogTextEdit(QtWidgets.QPlainTextEdit):
    def write(self, message):
        if not hasattr(self, "flag"):
            self.flag = False
        message = message.replace('\r', '').rstrip()
        if message:
            method = "replace_last_line" if self.flag else "appendPlainText"
            QtCore.QMetaObject.invokeMethod(self,
                method,
                QtCore.Qt.QueuedConnection, 
                QtCore.Q_ARG(str, message))
            self.flag = True
        else:
            self.flag = False

    @QtCore.pyqtSlot(str)
    def replace_last_line(self, text):
        cursor = self.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.select(QtGui.QTextCursor.BlockUnderCursor)
        cursor.removeSelectedText()
        cursor.insertBlock()
        self.setTextCursor(cursor)
        self.insertPlainText(text)

def foo(w):
    for i in tqdm(range(100), file=w):
        time.sleep(0.1)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = LogTextEdit(readOnly=True)
    w.appendPlainText(lorem.paragraph())
    w.appendHtml("Welcome to Stack Overflow")
    w.show()
    threading.Thread(target=foo, args=(w,), daemon=True).start()
    sys.exit(app.exec_())

关于python - 在 QPlainTextEdit 中使用 tqdm 显示终端输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53381975/

相关文章:

python - 如何在 PyQt 中更改 QInputDialog 的字体大小?

python - 使用 PySide 将 QImage 转为 Numpy 数组

qt - QML 不拥有从 PyQt 插槽接收的对象的所有权

python - 为什么这个函数会返回错误的结果?

python - 格式字符串的参数不足

python - PyQt QLineEdit 与历史记录

python - 如何获取加载图像的坐标而不是显示屏上的坐标

python - 如何在视频播放时通过 PyQt 从眼动仪中绘制眼睛注视数据

python - 使用 python 从 html 中删除/**/

python - Django 将对象列表转换为表格