我正在尝试制作一个 GUI 来更新我在 PyQT4 中的系统。我会让它在 GUI 中实时运行所有命令,以便您可以观看它的更新。我不确定我会使用什么类型的小部件来做到这一点。
这方面的一个例子是,wget 在运行时如何具有下载的状态栏,将其输出放入小部件中。
我会想象你会使用子进程库来运行命令,然后以某种方式将输出定向到小部件的内容,但我完全不确定如何做到这一点。
任何帮助都非常感谢。
你可以使用一个简单的QLabel
实例来完成这个任务。但是,如果您需要更花哨的可视化,您也可以选择只读QTextEdit
等。
至于处理代码,如果你碰巧选择QProcess
而不是python中的子流程模块,你会写一些类似于下面的代码的东西。
从 PyQt4.QtCore import QTimer, pyqtSignal, QProcess, pyqtSlot从 PyQt4.QtGui 导入 QLabel
class SystemUpdate(QProcess)
"""
A class used for handling the system update process
"""
def __init__(self):
_timer = QTimer()
_myDisplayWidget = QLabel()
self.buttonPressed.connect(self.handleReadyRead)
self.error.connect(self.handleError)
_timer.timeout.connect(self.handleTimeout)
_timer.start(5000)
@pyqtSlot()
def handleReadyRead(self):
_readData = readAll()
_myDisplayWidget.append(readData)
if not _timer.isActive():
_timer.start(5000)
@pyqtSlot()
def handleTimeout(self):
if not _readData:
_myDisplayWidget.append('No data was currently available for reading from the system update')
else:
_myDisplayWidget.append('Update successfully run')
@pyqtSlot(QProcess.ProcessError)
def handleError(self, processError)
if processError == QProcess.ReadError:
_myDisplayWidget.append('An I/O error occurred while reading the data, error: %s' % _process->errorString())
注意:我知道 QLabel
类没有附加方法,但是您可以借助可用方法轻松编写如此方便的包装器。
至于完整性,这里是python子过程方法:
import subprocess
from PyQt4.QtGui import QLabel
output = ""
try:
"""
Here you may need to pass the absolute path to the command
if that is not available in your PATH, although it should!
"""
output = subprocess.check_output(['command', 'arg1', 'arg2'], stderr=subprocess.STDOUT)
exception subprocess.CalledProcessError as e:
output = e.output
finally:
myDisplayWidget.append(output)