设计一个PyQt界面,用QProcess类来启动和管理Nginx进程:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import QProcess
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.process = QProcess(self)
self.nginx_running = False
def initUI(self):
self.start_stop_btn = QPushButton('启动Nginx', self)
self.start_stop_btn.clicked.connect(self.toggle_nginx)
self.start_stop_btn.resize(self.start_stop_btn.sizeHint())
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Nginx Controller')
self.show()
def toggle_nginx(self):
if self.nginx_running:
self.process.terminate()
self.nginx_running = False
self.start_stop_btn.setText('启动Nginx')
else:
self.process.start('path_to_nginx', ['-c', 'path_to_nginx_conf'])
self.nginx_running = True
self.start_stop_btn.setText('停止Nginx')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
path_to_nginx和path_to_nginx_conf换成你的Nginx的可执行文件路径和配置文件路径。
或者用楼上说的pid:
import sys
import os
import signal
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.pid = None
def initUI(self):
self.start_stop_btn = QPushButton('启动Nginx', self)
self.start_stop_btn.clicked.connect(self.toggle_nginx)
self.start_stop_btn.resize(self.start_stop_btn.sizeHint())
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Nginx Controller')
self.show()
def toggle_nginx(self):
if self.pid:
os.kill(self.pid, signal.SIGTERM) # 使用SIGTERM信号结束进程
self.pid = None
self.start_stop_btn.setText('启动Nginx')
else:
self.pid = os.spawnl(os.P_NOWAIT, 'path_to_nginx', 'nginx', '-c', 'path_to_nginx_conf')
self.start_stop_btn.setText('停止Nginx')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())