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()
相关推荐
羲云网络2 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗4 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn4 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_4047 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_7 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶7 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
geovindu9 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816310 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾11 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
卷无止境11 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python