当前位置: 首页 > 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.lryc.cn/news/571864.html

相关文章:

  • C++ 进阶:深入理解虚函数、继承与多态
  • 管件接头的无序抓取
  • C++11中alignof和alignas的入门到精通指南
  • 大语言模型指令集全解析
  • ATX电源
  • Java 淘宝商品详情接口实战解析
  • 小白成长之路-Rsync+sersync实现数据实时同步
  • 基于集体智能长尾识别的超声乳腺病变亚型分类|文献速递-深度学习医疗AI最新文献
  • 从零接入高德路径规划2.0:实现精准物流距离计算实战
  • FPGA基础 -- Verilog行为级建模之initial语句
  • C++11 移动语义详解
  • 基于大模型的胆囊结石全周期诊疗方案研究报告
  • vue3 javascript 多字段求和技巧
  • BitsAndBytes(简称 BnB)是一个用于“压缩”大语言模型的工具包
  • OpenStack入门
  • Karate UI 基本概念之一
  • python校园服务交流系统
  • 自动打电话软件设计与实现
  • cloudera manager 页面启动nodemanager失败,后端没有启动 8040
  • Python装饰器decorators和pytest夹具fixture详解和使用
  • 【强化学习】【笔记】【ch.10】GRPO / DAPO - 目前最优强化微调算法
  • openEuler安装BenchmarkSQL
  • AI Agent 与 Agentic AI 有何不同?
  • 7.索引库操作
  • 代码随想录算法训练营day8
  • 前端打断点
  • SSRF7 SSRF漏洞的检测方式
  • Uniapp 中根据不同离开页面方式处理 `onHide` 的方法
  • 意法STM32F103C8T6 单片机ARM Cortex-M3 国民MCU 电机控制到物联网专用
  • Ubuntu22.04安装opengauss并配置远程访问、JDBC连接