如何将 Python 脚本输出重定向到 PyQT5 GUI 控制台,而无需单击任何按钮? [英] How to redirect Python script output to PyQT5 GUI Console, without any buttons clicks?
问题描述
嘿,我使用相同的旧代码来获取所有代码输出 PyQT5 QTexBrowser GUI 控制台,但我也在所有新行中获取下一行字符(\n").
代码 URL -
有没有办法从参数中删除 "\n"
,请提出建议.
当我使用下面的行时,我能够看到每个新参数中都有 "\n"
.
self.view.append(str([*args]))
带有可见 "\n"
的 GUI 控制台输出(* 忽略行中的数字作为第一个字符 - 这是用户选择输出的一部分.)
然后我想尽一切可能的方法来删除像strip()、lstrip()等,仍然没有成功.
下面是代码的一部分,我如何将运行时输出重定向到 QtextBrowser
self.execution_result = QtWidgets.QWidget()self.execution_result.setObjectName("execution_result")self.execution_rslt_saveresult_btn = QtWidgets.QPushButton(self.execution_result)self.execution_rslt_saveresult_btn.setGeometry(QtCore.QRect(1220, 780, 131, 25))self.execution_rslt_saveresult_btn.setObjectName(execution_rslt_saveresult_btn")# ------------------------------------------------------------------------------------------------------## 控制台输出# ------------------------------------------------------------------------------------------------------#self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(2, 1, 1371, 771))self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")self.execution_rslt_textbrowser.setStyleSheet("""QTextBrowser {background-color: #000000;颜色:#00FF00;字体:11pt Courier new;}""")self.execution_rslt_textbrowser.document().setPlainText(——"* 40 + '\n' + "日志从下面的行开始+ '\n' + "-";* 40)# ------------------------------------------------------------------------------------------------------## 下面这行是将运行时输出发送到 GUI 控制台# ------------------------------------------------------------------------------------------------------#sys.stdout = 端口(self.execution_rslt_textbrowser)
请任何人建议我应该怎么做才能从输出行中删除 "\n"
.还有如何删除错误 AttributeError: 'port' object has no attribute 'flush'
以下是下一行字符问题的工作示例代码.- 供参考/调试
from PyQt5 import QtCore, QtGui, QtWidgets导入系统类端口(对象):def __init__(self, view):self.view = 查看def冲洗(自我):经过def write(self, *args):# self.view.append(str([*args])) # 这一行将突出显示控制台中的下一行字符\n";self.view.append(*args)类 Ui_MainWindow(对象):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")# MainWindow.setEnabled(True)MainWindow.resize(1000, 500)sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)sizePolicy.setHorizontalStretch(0)sizePolicy.setVerticalStretch(0)sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())MainWindow.setSizePolicy(sizePolicy)MainWindow.setMinimumSize(QtCore.QSize(1000, 500))MainWindow.setMaximumSize(QtCore.QSize(1000, 500))MainWindow.setBaseSize(QtCore.QSize(1000, 500))self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setMinimumSize(QtCore.QSize(0, 883))self.centralwidget.setObjectName("centralwidget")self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)self.tabWidget.setGeometry(QtCore.QRect(280, 0, 671, 341))self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)self.tabWidget.setDocumentMode(False)self.tabWidget.setTabsClosable(False)self.tabWidget.setObjectName("tabWidget")self.execution_result = QtWidgets.QWidget()self.execution_result.setObjectName("execution_result")self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(1, 1, 681, 321))self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")self.execution_rslt_textbrowser.document().setPlainText(——"* 40 + '\n' + "日志从下面的行开始+ '\n' + "-";* 40)# ----------------------------------------------------------------------------## 控制台输出重定向# ----------------------------------------------------------------------------#sys.stdout = 端口(self.execution_rslt_textbrowser)# ----------------------------------------------------------------------------#self.tabWidget.addTab(self.execution_result, "")self.mainwindow_list = QtWidgets.QListWidget(self.centralwidget)self.mainwindow_list.setGeometry(QtCore.QRect(20, 30, 241, 301))self.mainwindow_list.setObjectName("mainwindow_list")self.mainwindow_list.itemClicked['QListWidgetItem*'].connect(self.qlistoptions)item = QtWidgets.QListWidgetItem()字体 = QtGui.QFont()font.setPointSize(9)item.setFont(字体)self.mainwindow_list.addItem(item)item = QtWidgets.QListWidgetItem()字体 = QtGui.QFont()font.setPointSize(9)item.setFont(字体)self.mainwindow_list.addItem(item)item = QtWidgets.QListWidgetItem()字体 = QtGui.QFont()font.setPointSize(9)item.setFont(字体)self.mainwindow_list.addItem(item)item = QtWidgets.QListWidgetItem()字体 = QtGui.QFont()font.setPointSize(9)item.setFont(字体)self.mainwindow_list.addItem(item)MainWindow.setCentralWidget(self.centralwidget)self.retranslateUi(MainWindow)self.tabWidget.setCurrentIndex(0)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate(MainWindow", MainWindow"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.execution_result), _translate("MainWindow", "Execution Console"))__sortingEnabled = self.mainwindow_list.isSortingEnabled()self.mainwindow_list.setSortingEnabled(False)item = self.mainwindow_list.item(0)item.setText(_translate(MainWindow", Item1"))item = self.mainwindow_list.item(1)item.setText(_translate(MainWindow", Item2"))item = self.mainwindow_list.item(2)item.setText(_translate(MainWindow", Item3"))item = self.mainwindow_list.item(3)item.setText(_translate(MainWindow", Item4"))self.mainwindow_list.setSortingEnabled(__sortingEnabled)def qlistoptions(self):打印(在 qlistoptions 方法中:单击按钮")# window.hide() ## 关闭主窗口并打开新窗口.print(self.mainwindow_list.currentRow()) # 将返回列表项的索引号print(self.mainwindow_list.currentItem().text()) # 从列表项中返回当前选中的文本# 打印(信号-",self.mainwindow_ok.isChecked())# 项目 1如果 self.mainwindow_list.currentRow() == 0:打印(Item1被点击了!!")# 项目 2elif self.mainwindow_list.currentRow() == 1:打印(Item2被点击了!!")# 项目 3elif self.mainwindow_list.currentRow() == 2:打印(Item3被点击了!!")# 项目 4elif self.mainwindow_list.currentRow() == 3:打印(Item4被点击了!!")别的:打印(请先选择任何项目!!")def printText(self, button):print("来自printText方法的值-")打印(按钮.文本())如果 __name__ == __main__":app = QtWidgets.QApplication(sys.argv)MainWindow = QtWidgets.QMainWindow()ui = Ui_MainWindow()ui.setupUi(主窗口)MainWindow.show()sys.exit(app.exec_())
append方法添加了额外的endline,解决方法是插入文本不添加:
类端口(对象):def __init__(self, view):self.view = 查看def冲洗(自我):经过定义写(自我,文本):光标 = self.view.textCursor()cursor.movePosition(QtGui.QTextCursor.End)cursor.insertText(文本)self.view.setTextCursor(光标)self.view.ensureCursorVisible()
Hey I am using the same old code for getting all the code outputs PyQT5 QTexBrowser GUI console, but I am also getting next line character ("\n") in all new lines.
Code URL - pipe the output of sys.stdout to text browser in pyqt
Below is the code I am using from above URL -
class Port(object):
def __init__(self, view):
self.view = view
def write(self, *args):
# self.view.append(str([*args]))
# self.view.append(str(*args).rstrip("\n").lstrip("\n"))
self.view.append(*args)
GUI Console Output -
Is there any way to remove "\n"
from the args, Please suggest.
when I used below line, then I was able to see that there is "\n"
in every new args.
self.view.append(str([*args]))
GUI Console Output with visible "\n"
(* Ignore the numbers in lines as first character - that is part of user selection output.)
then I tried to do every possible way to remove like strip(), lstrip() etc, still didn't get success.
Below is the part of code, how I am redirecting run time output to QtextBrowser
self.execution_result = QtWidgets.QWidget()
self.execution_result.setObjectName("execution_result")
self.execution_rslt_saveresult_btn = QtWidgets.QPushButton(self.execution_result)
self.execution_rslt_saveresult_btn.setGeometry(QtCore.QRect(1220, 780, 131, 25))
self.execution_rslt_saveresult_btn.setObjectName("execution_rslt_saveresult_btn")
# ------------------------------------------------------------------------------------------------------#
# Console Output
# ------------------------------------------------------------------------------------------------------#
self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)
self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(2, 1, 1371, 771))
self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")
self.execution_rslt_textbrowser.setStyleSheet(
"""QTextBrowser {background-color: #000000;
color: #00FF00;
font: 11pt Courier new;}""")
self.execution_rslt_textbrowser.document().setPlainText(
"-" * 40 + '\n' + " Log starts from below line " + '\n' + "-" * 40)
# ------------------------------------------------------------------------------------------------------#
# Below line is sending run time output to GUI console
# ------------------------------------------------------------------------------------------------------#
sys.stdout = Port(self.execution_rslt_textbrowser)
Please anyone suggest what should I do here to remove "\n"
from the outputlines.
also how to remove error AttributeError: 'port' object has no attribute 'flush'
Below is the working sample code with next line character issue. - For reference/debugging
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Port(object):
def __init__(self, view):
self.view = view
def flush(self):
pass
def write(self, *args):
# self.view.append(str([*args])) # This line will highlight next line character in console "\n"
self.view.append(*args)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
# MainWindow.setEnabled(True)
MainWindow.resize(1000, 500)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(1000, 500))
MainWindow.setMaximumSize(QtCore.QSize(1000, 500))
MainWindow.setBaseSize(QtCore.QSize(1000, 500))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMinimumSize(QtCore.QSize(0, 883))
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(280, 0, 671, 341))
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tabWidget.setDocumentMode(False)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setObjectName("tabWidget")
self.execution_result = QtWidgets.QWidget()
self.execution_result.setObjectName("execution_result")
self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)
self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(1, 1, 681, 321))
self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")
self.execution_rslt_textbrowser.document().setPlainText(
"-" * 40 + '\n' + " Log starts from below line " + '\n' + "-" * 40)
# ----------------------------------------------------------------------------#
# Console Output Redirection
# ----------------------------------------------------------------------------#
sys.stdout = Port(self.execution_rslt_textbrowser)
# ----------------------------------------------------------------------------#
self.tabWidget.addTab(self.execution_result, "")
self.mainwindow_list = QtWidgets.QListWidget(self.centralwidget)
self.mainwindow_list.setGeometry(QtCore.QRect(20, 30, 241, 301))
self.mainwindow_list.setObjectName("mainwindow_list")
self.mainwindow_list.itemClicked['QListWidgetItem*'].connect(self.qlistoptions)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.execution_result), _translate("MainWindow", "Execution Console"))
__sortingEnabled = self.mainwindow_list.isSortingEnabled()
self.mainwindow_list.setSortingEnabled(False)
item = self.mainwindow_list.item(0)
item.setText(_translate("MainWindow", "Item1"))
item = self.mainwindow_list.item(1)
item.setText(_translate("MainWindow", "Item2"))
item = self.mainwindow_list.item(2)
item.setText(_translate("MainWindow", "Item3"))
item = self.mainwindow_list.item(3)
item.setText(_translate("MainWindow", "Item4"))
self.mainwindow_list.setSortingEnabled(__sortingEnabled)
def qlistoptions(self):
print("Inside qlistoptions method : Button Clicked")
# window.hide() ## This to close main window and open new window.
print(self.mainwindow_list.currentRow()) # Will Return Index number of list item
print(self.mainwindow_list.currentItem().text()) # Will Return current selected text from list item
# print("Signal-", self.mainwindow_ok.isChecked())
# Item1
if self.mainwindow_list.currentRow() == 0:
print("Item1 is Clicked!!")
# Item2
elif self.mainwindow_list.currentRow() == 1:
print("Item2 is Clicked!!")
# Item3
elif self.mainwindow_list.currentRow() == 2:
print("Item3 is Clicked!!")
# Item4
elif self.mainwindow_list.currentRow() == 3:
print("Item4 is Clicked!!")
else:
print("Please select any item first!!")
def printText(self, button):
print("Value from printText Method -")
print(button.text())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The append method adds an additional endline, the solution is to insert the text without adding it:
class Port(object):
def __init__(self, view):
self.view = view
def flush(self):
pass
def write(self, text):
cursor = self.view.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.view.setTextCursor(cursor)
self.view.ensureCursorVisible()
这篇关于如何将 Python 脚本输出重定向到 PyQT5 GUI 控制台,而无需单击任何按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!