【python学习案例】python判断自身是否正在运行
需要引入psutil包;
实现思路:
1)用os.getpid()获取当前程序运行PID,将PID存入文件中
2)用psutil模块获取当前系统所有正在运行的pid
3)读取之前存入的PID,判断该PID是否在系统PID中
4)如果文件中的PID在系统PID中,则退出程序,否则存入新的PID,运行程序。
# -*- coding:utf-8 -*- import os import psutil import time def write_pid(): pid = os.getpid() fp = open("pid.log",'w') fp.write(str(pid)) fp.close() def read_pid(): if os.path.exists("pid.log"): fp = open("pid.log",'r') pid = fp.read() fp.close() return pid else: return False def write_log(log_content): time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) log_content = time_now+"---->"+log_content+os.linesep fp = open('recognition.log','a+') fp.write(log_content) fp.close() def run(): pid = read_pid() #print pid pid = int(pid) if pid: running_pid = psutil.pids() if pid in running_pid: log_content = "process is running..." write_log(log_content) else: write_pid() time.sleep(20) else: print "process is not running..." write_pid() time.sleep(20) if __name__ == "__main__": run()
学习技术不是用来写HelloWorld和Demo的,而是要用来解决线上系统的真实问题的.
分类:
【06】Python
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束