使用pyside2實現一個終端顯示工具
使用pyside2實現一個實時終端顯示工具
目標
通常很多終端執行的指令都是一直長時間運行的,這種情況如何將終端返回的結果顯示在gui界面上,如:ping www.baidu.com等操作。最終目的是通過點擊一個按鈕,將終端的持續輸出結果顯示在一個文本輸入框裏。
使用到的技術
- pyside2的Signal和Slot
- python的subprocess和threading
核心代碼
定義信號(Signal)
# Ui_Main後的參數一定要改爲QObject,否則就會提示Signal沒有connect和emit這些屬性
class Ui_Main(QObject):
#定義你的信號
output_str = QtCore.Signal(str)
定義槽函數與相關函數(Slot)
# 按鈕點擊觸發的函數
def start_thread(self):
# 創建線程執行函數
t1 = th.Thread(target=self.output)
print("start")
t1.start()
# 執行shell指令
def output(self):
for path in self.run("ping -c 5 google.com"):
# 發送信號,將終端的返回值作爲參數
self.output_str.emit(str(path)+'\n')
# shell執行函數,支持長時間運行
def run(self, command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
while True:
line = process.stdout.readline().rstrip()
if not line:
break
yield line
# 用於接受信號數據的槽函數
@Slot(str)
def update(self,str):
print(str)
# 在文本輸入框末尾添加新收到的字符數據
self.textEdit.insertPlainText(str)
在相關界面代碼中加入綁定代碼
# 按鈕點擊事件綁定start_thread函數
self.pushButton.clicked.connect(self.start_thread)
# output_str信號綁定update函數
self.output_str.connect(self.update)
測試結果
- 點擊執行按鈕
2. 查看輸出結果
pyside2-uic命令(ui文件轉python文件)
pyside2-uic mainwindow.ui > ui_mainwindow.py