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()
相关推荐
宇寒风暖1 小时前
Flask 框架全面详解
笔记·后端·python·学习·flask·知识
seabirdssss1 小时前
错误: 找不到或无法加载主类 原因: java.lang.ClassNotFoundException
java·开发语言
哪 吒1 小时前
【2025C卷】华为OD机试九日集训第3期 - 按算法分类,由易到难,提升编程能力和解题技巧
python·算法·华为od·华为od机试·2025c卷
gnawkhhkwang1 小时前
io_getevents 和 io_pgetevents 系统调用及示例
linux·c语言·开发语言
喵手1 小时前
使用ASIWebPageRequest库编写Objective-C下载器程序
开发语言·macos·objective-c
weixin_456904271 小时前
C#泛型委托讲解
开发语言·c#
君莫笑几人回2 小时前
关于记录一下“bug”,在做图片上传的时候出现的小问题
java·开发语言·spring boot
rockmelodies2 小时前
RSA 解密逻辑
开发语言·python
澡点睡觉3 小时前
golang的包和闭包
开发语言·后端·golang
Tobiichiorigami.3 小时前
Python训练Day30
python