python3:线程管理进程

1、主线程启动/停止子线程

2、子线程拉起/停止工作的进程,并负责信息记录

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""

"""
import os
import subprocess
import threading
import time


class CmdThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()
        self._proc = None

    def run(self):
        # 运行命令(例如 ping)
        process = subprocess.Popen(
            ['ping', 'www.baidu.com'],
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        while True:
            if self._stop_event.is_set():
                process.terminate()
                # 等待命令执行完成并获取返回码
                return_code = process.wait()
                print(f"命令返回码: {return_code}")
                break
            return_code = process.poll()
            if return_code is not None:
                print(f"命令返回码: {return_code}")
                break

            line = process.stdout.readline()
            if not line:
                time.sleep(0.5)
                thread = threading.current_thread()
                print(time.strftime("%H:%M:%S"), f"子线程<{os.getpid()}-{thread.ident}>正在运行...")
            print(f"输出<{process.pid}>: {line.strip()}", process.poll())

        thread = threading.current_thread()
        print(time.strftime("%H:%M:%S"), f"子线程<{os.getpid()}-{thread.ident}>已停止")

    def stop(self):
        self._stop_event.set()


class ManageServer:
    def __init__(self):
        self._child_thread = [CmdThread(), CmdThread()]

    def start_all_servers(self):
        for child in self._child_thread:
            child.start()

        # 主线程执行其他操作
        for i in range(10):
            thread = threading.current_thread()
            print(time.strftime("%H:%M:%S"), f"主线程<{os.getpid()}-{thread.ident}>", i)
            time.sleep(5)

        print(time.strftime("%H:%M:%S"), f"所有子线程启动完毕!!")

    def stop_all_servers(self):
        for child in self._child_thread:
            child.stop()
        for child in self._child_thread:
            child.join()
        print(time.strftime("%H:%M:%S"), f"所有子线程已结束")


def main_run():
    """主函数"""
    ms = ManageServer()
    try:
        ms.start_all_servers()
    except KeyboardInterrupt:
        # 停止线程
        ms.stop_all_servers()
        print("主线程已结束")


if __name__ == "__main__":
    main_run()
相关推荐
爱吃小胖橘23 分钟前
Lua语法(2)
开发语言·unity·lua
_Power_Y25 分钟前
SSM面试题学习
java·开发语言·学习
Pocker_Spades_A36 分钟前
中秋与代码共舞:用Python、JS、Java打造你的专属中秋技术盛宴
python
梁萌1 小时前
自动化测试框架playwright使用
自动化测试·python·ui自动化·playwright
SccTsAxR1 小时前
[初学C语言]关于scanf和printf函数
c语言·开发语言·经验分享·笔记·其他
Python×CATIA工业智造1 小时前
Python回调函数中携带额外状态的完整指南:从基础到高级实践
python·pycharm
害恶细君1 小时前
【超详细】使用conda配置python的开发环境
开发语言·python·jupyter·pycharm·conda·ipython
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 变量(Variable)的定义与操作
python·深度学习·tensorflow·tensorflow2
我星期八休息2 小时前
C++异常处理全面解析:从基础到应用
java·开发语言·c++·人工智能·python·架构
2401_841495642 小时前
【数据结构】汉诺塔问题
java·数据结构·c++·python·算法·递归·