当前位置: 首页 > 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()

相关文章:

  • 基于深度学习的智能图像风格转换系统:技术与实践
  • 逆向分析贝壳网人机验证JS加密逻辑
  • macos电脑本地搭建mistral-7b大模型出现4-bit量化和缓存不足问题的记录
  • leetcode-3405 统计恰好有k个相等相邻数组的个数
  • CSPNet: 一种增强CNN学习能力的新型骨干网络
  • 设置环境变量(linux,windows,windows用指令和用界面)
  • C2远控篇CC++InlineHook挂钩动态API调用突破内存加密导入表检测
  • milvus和attu的搭建
  • AIRTBench:测量语言模型中的自主 AI 红队功能
  • Uniapp 中 onShow 与 onLoad 的执行时机解析
  • MacOS X 命令行永久设置网卡IP、MASK、GW、DNS
  • uni-app总结3-项目新建运行调试
  • easyexcel基于模板生成报表
  • kafka消费的模式及消息积压处理方案
  • 【系统分析师】2015年真题:案例分析-答案及详解
  • 【隐马尔可夫模型】隐马尔可夫模型的观测序列概率计算算法及例题详解
  • 【一天一个知识点】RAG系统构建第二步:构建检索器模块(Retriever)
  • 电路笔记(信号):一阶低通RC滤波器 一阶线性微分方程推导 拉普拉斯域表达(传递函数、频率响应)分析
  • 京东三年一革新:宣布进军酒旅行业,携程回应海外市场巨大
  • Seo工具使用与流量数据观察实践(上)
  • 境外电商网站建设/中关村标准化协会
  • 网站建设服务网站建设/站长工具一区
  • 做网站网页排版错误/西安高端网站建设公司
  • 上海网站设计团队/产品推广软文200字
  • 四川建设工程网上合同备案网站/如何推广普通话的建议6条
  • wordpress 图片库/什么是搜索引擎优化