pyqt 启动GUI前启动子进程,退出GUI后退出子进程

先贴代码
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
#import test     # module test.py
from main import MainWindow 
import subprocess
import psutil
from config import config

def close_process(p1):
    pobj1 = psutil.Process(p1.pid)
    # list children & kill them
    for c in pobj1.children(recursive=True):
        c.kill()
    pobj1.kill()

if __name__ == '__main__':
    #启动udp服务器
    #p1 = subprocess.Popen('.\start_image.bat', creationflags =subprocess.CREATE_NEW_CONSOLE)
    #p2 = subprocess.Popen('.\start_motor.bat', creationflags =subprocess.CREATE_NEW_CONSOLE)
    #p1 = subprocess.Popen('.\start_image.bat', shell=True)
    #p2 = subprocess.Popen('.\start_motor.bat', shell=True)
    p_subs = []
    for name, PARA in config['SUB_PROCESSES'].items():
        CMD = PARA['CMD']
        CWD = PARA['CWD']
        if CMD != '':
            print(CMD)
            print(CWD)
            p_sub1 = subprocess.Popen(CMD, cwd=CWD, shell=True)
            p_subs.append(p_sub1)
    
    #print(p1.pid)
    app = QApplication(sys.argv)
    myMainWindow = MainWindow()


    myMainWindow.show()

    p_main = app.exec_()

    print('执行到这里')

    [close_process(p1) for p1 in p_subs]

    sys.exit(p_main)

 

   

1 subprocess.Popen

https://docs.python.org/3.8/library/subprocess.html#subprocess.STARTF_USESHOWWINDOW

取代了原来的N种spwan  os.popen什么的

cwd 指定工作路径, shell=True 让子进程在任务管理器里位于当前进程Python下。而不是散放着   但启动新窗口  subprocess.CREATE_NEW_CONSOLE 没实验成功,提示   FileNotFoundError: [WinError 2] 系统找不到指定的文件。

2 关闭子进程

用到了psutil, 且保证把子进程的子进程也关闭了   3 改写qt的结束语句 一般都是写成 sys.exit(app.exec_()) 这样是不会执行到后面的。所以得拆开写。    
上一篇:Python 常用的GUI框架都有哪些?


下一篇:Pyqt 开发环境准备