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()
相关推荐
消失的旧时光-194318 小时前
Java 线程池(第四篇):ScheduledThreadPoolExecutor 原理与定时任务执行机制全解析
java·开发语言
dudke19 小时前
js的reduce详解
开发语言·javascript·ecmascript
kevin_水滴石穿19 小时前
docker-compose.yml案例
java·服务器·开发语言
coderxiaohan19 小时前
【C++】用哈希表封装unordered_map和unordered_set
开发语言·c++·散列表
谈笑也风生19 小时前
验证IP地址(三)
python·tcp/ip·mysql
梦幻精灵_cq19 小时前
code-word.csv开始记录——我的new“工程”启动
python
清水白石00819 小时前
《Python 分布式锁全景解析:从基础原理到实战最佳实践》
开发语言·分布式·python
沈浩(种子思维作者)19 小时前
道AI能不能帮助造出黄金?
人工智能·python
曲幽19 小时前
Python新利器:用uv轻松管理venv虚拟环境和pip依赖包
python·pip·uv·init·venv
西猫雷婶19 小时前
卷积运算效果的池化处理|最大值
人工智能·pytorch·python·深度学习·神经网络·机器学习·cnn