问题
I'm importing files to a MySQL DB using the LOAD DATA INFILE command
.
Some files may have an error which results in a console message like:
mysql.connector.errors.DatabaseError: 1265 (01000): Data truncated for column 'z' at row x
How can I put this error message to a QMessageBox
so the user of the .exe has an indicator where to check the dataset?
try:
cursor.execute(query)
except:
QMessageBox.warning(self, "Failure", ...Console Output...)
回答1:
If the SQL library is using standard Python output, you could try to overwrite sys.stderr
and sys.stdout
with any object that implements a write method:
import sys
class TextBoxStderr:
def __init__(self):
self.textbox = QTextEdit()
def write(self, errmsg):
self.textbox.append(errmsg)
box_stderr = TextBoxStderr()
sys.stderr = box_stderr
# ... Call Import Operation ...
# If any error was appended to the text box, show it
if box_stderr.textbox.toPlainText():
box_stderr.textbox.show()
Any text sent to stderr will be appended to a QTextEdit. Make sure you rollback the original object after the operation is complete:
sys.sterr = sys.__stderr__
来源:https://stackoverflow.com/questions/24017143/display-python-console-messages-in-qmessagebox