【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()
复制代码

 

posted @   cac2020  阅读(1263)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束
点击右上角即可分享
微信分享提示