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()
相关推荐
fenglllle7 分钟前
JDK8升级JDK17使用CompletableFuture在线程中classloader的变化
java·开发语言·jvm
不懒不懒7 分钟前
Python+AI 大模型实现课堂教学质量智能分析|加权评分 + 自动诊断 + 改进建议
人工智能·python·深度学习·ai大模型·智慧教育·nlp算法
froginwe118 分钟前
Scala 正则表达式
开发语言
时寒的笔记9 分钟前
11期_js逆向核心案例解析(sichuan&某理财网)
开发语言·javascript·ecmascript
csbysj202011 分钟前
PHP 文件:深入解析与最佳实践
开发语言
JAVA面经实录91716 分钟前
Java+SpringAI企业级实战项目完整官方文档(生产终版)
java·开发语言·spring·ai编程
梵得儿SHI16 分钟前
Java IO 流进阶:Buffer 与 Channel 核心概念解析及与传统 IO 的本质区别
java·开发语言·高并发·nio·channel·buffer·提升io效率
j_xxx404_19 分钟前
Linux线程:从内存分页机制(Page Table/TLB/Page Fault)彻底读懂 Linux 线程本质
linux·运维·服务器·开发语言·c++·人工智能·ai
小新同学^O^19 分钟前
OpenClaw 数据采集工具新手入门指南
python·学习·openclaw·纯ai文
2301_7890156221 分钟前
C++_string增删查改模拟实现
java·开发语言·c++