当前位置: 首页 > news >正文

python3:线程管理进程

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-""""""
import os
import subprocess
import threading
import timeclass CmdThread(threading.Thread):def __init__(self):super().__init__()self._stop_event = threading.Event()self._proc = Nonedef 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}")breakreturn_code = process.poll()if return_code is not None:print(f"命令返回码: {return_code}")breakline = 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()
http://www.xdnf.cn/news/1059013.html

相关文章:

  • 前端打断点
  • python校园服务交流系统
  • 第十八天:初级数据库学习笔记2
  • easyexcel基于模板生成报表
  • RabbitMQ七种工作模式
  • 21.加密系统函数
  • macOS版的节点小宝上架苹果APP Store了
  • git的使用——初步认识git和基础操作
  • DeepForest开源程序是用于 Airborne RGB 机器学习的 Python 软件包
  • 使用 Elasticsearch 提升 Copilot 能力
  • [计算机网络] 网络的诞生:协议的认知建立
  • 2025年暑期在线实习项目分享
  • 理解 create 指向的箭头函数
  • 从零Gazebo中实现Cartographer算法建图
  • DBeaver 中 Greenplum、PostgreSQL 和 PostgreSQL (old) 驱动的区别
  • 前端跨域解决方案(4):postMessage
  • 剑指offer32_二叉搜索树的后序遍历序列
  • 新发布的一款使用ReactNative新架构加载Svga动画的开源插件[android/ios]
  • 数据结构——选择题—查漏补缺
  • 【unitrix】 3.0 基本结构体(types.rs)
  • 二、OpenCV的第一个程序
  • Uniapp H5端SEO优化全攻略:提升搜索引擎排名与流量
  • 结合 STM32CubeMX 使用 FreeRTOS 实时操作系统
  • 【ClipPal】推荐一个非常好用的粘贴板记录工具
  • 侧信道分析中的简单模板攻击(TA)Python实现(带测试)
  • 【web应用】Vue 3 中实现 Chart.js 折线图:详细指南与最佳实践
  • 14.2 《3小时从零搭建企业级LLaMA3语言助手:GitHub配置+私有化模型集成全实战》
  • 基于CNN的FashionMNIST数据集识别6——DenseNet模型
  • 基于深度学习的智能文本摘要系统:技术与实践
  • Uniapp性能优化全面指南:从原理到实践