11import threading
2+ import warnings
23
4+ from qtpy import QtCore
35from qtpy .QtGui import QTextCursor
46from qtpy .QtWidgets import QTextEdit
57
@@ -22,23 +24,66 @@ def __init__(self, parent):
2224
2325 # def receive_log(self, text):
2426 # self.print_and_log(text)
27+ def write (self , message ):
28+ self .lock .acquire ()
29+ try :
30+ if not hasattr (self , "flag" ):
31+ self .flag = False
32+ message = message .replace ("\r " , "" ).rstrip ()
33+ if message :
34+ method = "replace_last_line" if self .flag else "append"
35+ QtCore .QMetaObject .invokeMethod (
36+ self ,
37+ method ,
38+ QtCore .Qt .QueuedConnection ,
39+ QtCore .Q_ARG (str , message ),
40+ )
41+ self .flag = True
42+ else :
43+ self .flag = False
44+
45+ finally :
46+ self .lock .release ()
2547
26- def print_and_log (self , text ):
48+ @QtCore .Slot (str )
49+ def replace_last_line (self , text ):
50+ self .lock .acquire ()
51+ try :
52+ cursor = self .textCursor ()
53+ cursor .movePosition (QTextCursor .End )
54+ cursor .select (QTextCursor .BlockUnderCursor )
55+ cursor .removeSelectedText ()
56+ cursor .insertBlock ()
57+ self .setTextCursor (cursor )
58+ self .insertPlainText (text )
59+ finally :
60+ self .lock .release ()
61+
62+ def print_and_log (self , text , printing = True ):
2763 """Utility used to both print to terminal and log text to a QTextEdit
2864 item in a thread-safe manner. Use only for important user info.
2965
3066 Args:
3167 text (str): Text to be printed and logged
68+ printing (bool): Whether to print the message as well or not using print(). Defaults to True.
3269
3370 """
3471 self .lock .acquire ()
3572 try :
36- print (text )
37- # causes issue if you clik on terminal (tied to CMD QuickEdit mode)
73+ if printing :
74+ print (text )
75+ # causes issue if you clik on terminal (tied to CMD QuickEdit mode on Windows)
3876 self .moveCursor (QTextCursor .End )
3977 self .insertPlainText (f"\n { text } " )
4078 self .verticalScrollBar ().setValue (
4179 self .verticalScrollBar ().maximum ()
4280 )
4381 finally :
4482 self .lock .release ()
83+
84+ def warn (self , warning ):
85+ self .lock .acquire ()
86+ try :
87+ warnings .warn (warning )
88+ finally :
89+ self .lock .release ()
0 commit comments