Display terminal output with tqdm in QPlainTextEdit












1















I'm trying to find a way of getting, along with other prints, the result/evolution of a progress bar in a pyqt application, for example in a QPlainTextEdit widget.



The problem I'm facing, is that progress bars can use some more advanced carriage return, or even more advanced cursor positionning that are mostly not supported by treams.
I've tried io.StringIO, but the r is kept literal.



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


output:



s.getvalue()

Out[24]: 'nr 0%| | 0/3 [00:00<?, ?it/s]x1b[Anr 33%|###3 | 1/3 [00:00<00:00, 9.99it/s]x1b[Anr 67%|######6 | 2/3 [00:00<00:00, 9.98it/s]x1b[Anr100%|##########| 3/3 [00:00<00:00, 9.98it/s]x1b[Anx1b[A'


which translate into:



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]


To be clear, in my output, I don't want one line per tqdm update, but just the current state, as it would be printed on the command line.



Any idea o how to do this ?
Thanks!










share|improve this question

























  • what is text widget?

    – eyllanesc
    Nov 19 '18 at 20:47











  • any widget that display multiline text, for example QPlainTextEdit

    – beesleep
    Nov 19 '18 at 21:51











  • Do you want the next line to replace the previous one?

    – eyllanesc
    Nov 19 '18 at 21:53











  • Do you know that you should not use sleep in a GUI?

    – eyllanesc
    Nov 19 '18 at 22:04











  • yes, of course, that was for the purpose of demonstration.

    – beesleep
    Nov 19 '18 at 22:51
















1















I'm trying to find a way of getting, along with other prints, the result/evolution of a progress bar in a pyqt application, for example in a QPlainTextEdit widget.



The problem I'm facing, is that progress bars can use some more advanced carriage return, or even more advanced cursor positionning that are mostly not supported by treams.
I've tried io.StringIO, but the r is kept literal.



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


output:



s.getvalue()

Out[24]: 'nr 0%| | 0/3 [00:00<?, ?it/s]x1b[Anr 33%|###3 | 1/3 [00:00<00:00, 9.99it/s]x1b[Anr 67%|######6 | 2/3 [00:00<00:00, 9.98it/s]x1b[Anr100%|##########| 3/3 [00:00<00:00, 9.98it/s]x1b[Anx1b[A'


which translate into:



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]


To be clear, in my output, I don't want one line per tqdm update, but just the current state, as it would be printed on the command line.



Any idea o how to do this ?
Thanks!










share|improve this question

























  • what is text widget?

    – eyllanesc
    Nov 19 '18 at 20:47











  • any widget that display multiline text, for example QPlainTextEdit

    – beesleep
    Nov 19 '18 at 21:51











  • Do you want the next line to replace the previous one?

    – eyllanesc
    Nov 19 '18 at 21:53











  • Do you know that you should not use sleep in a GUI?

    – eyllanesc
    Nov 19 '18 at 22:04











  • yes, of course, that was for the purpose of demonstration.

    – beesleep
    Nov 19 '18 at 22:51














1












1








1








I'm trying to find a way of getting, along with other prints, the result/evolution of a progress bar in a pyqt application, for example in a QPlainTextEdit widget.



The problem I'm facing, is that progress bars can use some more advanced carriage return, or even more advanced cursor positionning that are mostly not supported by treams.
I've tried io.StringIO, but the r is kept literal.



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


output:



s.getvalue()

Out[24]: 'nr 0%| | 0/3 [00:00<?, ?it/s]x1b[Anr 33%|###3 | 1/3 [00:00<00:00, 9.99it/s]x1b[Anr 67%|######6 | 2/3 [00:00<00:00, 9.98it/s]x1b[Anr100%|##########| 3/3 [00:00<00:00, 9.98it/s]x1b[Anx1b[A'


which translate into:



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]


To be clear, in my output, I don't want one line per tqdm update, but just the current state, as it would be printed on the command line.



Any idea o how to do this ?
Thanks!










share|improve this question
















I'm trying to find a way of getting, along with other prints, the result/evolution of a progress bar in a pyqt application, for example in a QPlainTextEdit widget.



The problem I'm facing, is that progress bars can use some more advanced carriage return, or even more advanced cursor positionning that are mostly not supported by treams.
I've tried io.StringIO, but the r is kept literal.



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


output:



s.getvalue()

Out[24]: 'nr 0%| | 0/3 [00:00<?, ?it/s]x1b[Anr 33%|###3 | 1/3 [00:00<00:00, 9.99it/s]x1b[Anr 67%|######6 | 2/3 [00:00<00:00, 9.98it/s]x1b[Anr100%|##########| 3/3 [00:00<00:00, 9.98it/s]x1b[Anx1b[A'


which translate into:



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]


To be clear, in my output, I don't want one line per tqdm update, but just the current state, as it would be printed on the command line.



Any idea o how to do this ?
Thanks!







python pyqt pyqt5 tqdm qplaintextedit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 1:07









eyllanesc

77.2k103156




77.2k103156










asked Nov 19 '18 at 20:14









beesleepbeesleep

651312




651312













  • what is text widget?

    – eyllanesc
    Nov 19 '18 at 20:47











  • any widget that display multiline text, for example QPlainTextEdit

    – beesleep
    Nov 19 '18 at 21:51











  • Do you want the next line to replace the previous one?

    – eyllanesc
    Nov 19 '18 at 21:53











  • Do you know that you should not use sleep in a GUI?

    – eyllanesc
    Nov 19 '18 at 22:04











  • yes, of course, that was for the purpose of demonstration.

    – beesleep
    Nov 19 '18 at 22:51



















  • what is text widget?

    – eyllanesc
    Nov 19 '18 at 20:47











  • any widget that display multiline text, for example QPlainTextEdit

    – beesleep
    Nov 19 '18 at 21:51











  • Do you want the next line to replace the previous one?

    – eyllanesc
    Nov 19 '18 at 21:53











  • Do you know that you should not use sleep in a GUI?

    – eyllanesc
    Nov 19 '18 at 22:04











  • yes, of course, that was for the purpose of demonstration.

    – beesleep
    Nov 19 '18 at 22:51

















what is text widget?

– eyllanesc
Nov 19 '18 at 20:47





what is text widget?

– eyllanesc
Nov 19 '18 at 20:47













any widget that display multiline text, for example QPlainTextEdit

– beesleep
Nov 19 '18 at 21:51





any widget that display multiline text, for example QPlainTextEdit

– beesleep
Nov 19 '18 at 21:51













Do you want the next line to replace the previous one?

– eyllanesc
Nov 19 '18 at 21:53





Do you want the next line to replace the previous one?

– eyllanesc
Nov 19 '18 at 21:53













Do you know that you should not use sleep in a GUI?

– eyllanesc
Nov 19 '18 at 22:04





Do you know that you should not use sleep in a GUI?

– eyllanesc
Nov 19 '18 at 22:04













yes, of course, that was for the purpose of demonstration.

– beesleep
Nov 19 '18 at 22:51





yes, of course, that was for the purpose of demonstration.

– beesleep
Nov 19 '18 at 22:51












1 Answer
1






active

oldest

votes


















1














The idea is to remove the previous line if there is a new text added, but you must also remove r and verify that it is not an empty text. Also, for an object to receive the text of tqdm, it must only have the write() method, so implement a custom QPlainTextEdit. Use QMetaObject::invokeMethod() to make it thread-safe



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_())





share|improve this answer


























  • Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

    – beesleep
    Nov 19 '18 at 23:46











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381975%2fdisplay-terminal-output-with-tqdm-in-qplaintextedit%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














The idea is to remove the previous line if there is a new text added, but you must also remove r and verify that it is not an empty text. Also, for an object to receive the text of tqdm, it must only have the write() method, so implement a custom QPlainTextEdit. Use QMetaObject::invokeMethod() to make it thread-safe



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_())





share|improve this answer


























  • Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

    – beesleep
    Nov 19 '18 at 23:46
















1














The idea is to remove the previous line if there is a new text added, but you must also remove r and verify that it is not an empty text. Also, for an object to receive the text of tqdm, it must only have the write() method, so implement a custom QPlainTextEdit. Use QMetaObject::invokeMethod() to make it thread-safe



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_())





share|improve this answer


























  • Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

    – beesleep
    Nov 19 '18 at 23:46














1












1








1







The idea is to remove the previous line if there is a new text added, but you must also remove r and verify that it is not an empty text. Also, for an object to receive the text of tqdm, it must only have the write() method, so implement a custom QPlainTextEdit. Use QMetaObject::invokeMethod() to make it thread-safe



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_())





share|improve this answer















The idea is to remove the previous line if there is a new text added, but you must also remove r and verify that it is not an empty text. Also, for an object to receive the text of tqdm, it must only have the write() method, so implement a custom QPlainTextEdit. Use QMetaObject::invokeMethod() to make it thread-safe



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_())






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 '18 at 1:40

























answered Nov 19 '18 at 23:37









eyllanesceyllanesc

77.2k103156




77.2k103156













  • Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

    – beesleep
    Nov 19 '18 at 23:46



















  • Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

    – beesleep
    Nov 19 '18 at 23:46

















Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

– beesleep
Nov 19 '18 at 23:46





Thanks, I need a bit of time to test if it fits my need, but be sure I'll accept as soon as I got it working

– beesleep
Nov 19 '18 at 23:46


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381975%2fdisplay-terminal-output-with-tqdm-in-qplaintextedit%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents