实现一个简单的终端执行器
功能:
执行命令
显示结果
效果:
代码:
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import sys
import subprocess
class JTerminal(QMainWindow):
def __init__(self, parent=None):
super(JTerminal, self).__init__(parent)
self.initUI()
self.lineEdit.returnPressed.connect(self.doCommand)
self.working_dir = "."
def initUI(self):
self.setWindowTitle('JTerminal')
self.setGeometry(100, 100, 800, 600)
self.central = QWidget()
self.layout = QVBoxLayout()
self.textBrowser = QTextBrowser()
fontShow = QFont("DejaVu Sans Mono", 12)
self.textBrowser.setFont(fontShow)
fontInput = QFont("Monospace", 12)
self.lineEdit = QLineEdit()
self.lineEdit.setFont(fontInput)
self.layout.addWidget(self.textBrowser)
self.layout.addWidget(self.lineEdit)
self.central.setLayout(self.layout)
self.menuBar = QMenuBar()
self.menuBar.setGeometry(QRect(0, 0, 800, 26))
self.setMenuBar(self.menuBar)
self.setCentralWidget(self.central)
def doCommand(self):
cmd = self.lineEdit.text()
self.lineEdit.setText("")
result_pwd = subprocess.check_output("pwd", shell=True, cwd=self.working_dir)
self.textBrowser.setText(self.textBrowser.toPlainText() + result_pwd.decode('utf-8') + "> " + cmd + "\n")
if "cd" in cmd:
vals = cmd.split(" ")
if vals[1][0] == "/":
self.working_dir = vals[1]
else:
self.working_dir = self.working_dir + "/" + vals[1]
# subprocess.call(cmd, shell=True, cwd=self.working_dir)
#run 依赖python 3.5, 所以需要注意,call不需要
result = subprocess.run(cmd, shell=True, cwd=self.working_dir)
# self.textBrowser.setText(self.textBrowser.toPlainText() + "\n" + cmd)
result_pwd = subprocess.check_output("pwd", shell=True, cwd=self.working_dir)
self.textBrowser.setText(self.textBrowser.toPlainText() + result_pwd.decode('utf-8'))
else:
try:
result = subprocess.check_output(cmd, shell=True, cwd=self.working_dir)
self.textBrowser.setText(self.textBrowser.toPlainText() + result.decode('utf-8'))
except:
self.textBrowser.setText(self.textBrowser.toPlainText() + "command not found \n")
self.textBrowser.verticalScrollBar().setValue(self.textBrowser.verticalScrollBar().maximum())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = JTerminal()
ex.show()
sys.exit(app.exec())
代码地址:
GitHub - chunlaiqingke/Tiny-Tool
公众号
代码参考项目:
GitHub - petercour/terminal-emulator-example-pyqt: Terminal emulator in pyqt, https://pythonbasics.org/pyqt/