我正在尝试制作一个 GUI 来更新我在 PyQT4 中的系统。我想让它在 GUI 中实时运行所有命令,这样你就可以看到它的更新。我不确定要使用哪种类型的小部件。
这方面的一个例子就像 wget 在运行时如何具有下载的状态栏,将其输出放入一个小部件中。
我想您会使用子进程库来运行命令,然后以某种方式将输出定向到小部件的内容,但我完全不确定如何执行此操作。
非常感谢任何帮助。
请您参考如下方法:
我相信您可以使用一个简单的 QLabel
实例来完成这项任务。但是,如果您需要更精美的可视化效果,您也可以选择只读的 QTextEdit
等。
关于处理代码,如果你碰巧选择QProcess
而不是python中的subprocess模块,你会写类似下面的代码。
从 PyQt4.QtCore 导入 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)