zoukankan      html  css  js  c++  java
  • 【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()
  • 相关阅读:
    定制一个支持中英文的简单LaTex模板
    汉字hash问题(转)
    算法题之最大回文子串
    算法题之添加回文串
    数据表设计的步骤
    很简单的Java断点续传实现原理
    MongoDB 搭建文件存储的方案
    cron语法
    关于如何使用SVN的一些建议
    无后台应用 Stash Backend
  • 原文地址:https://www.cnblogs.com/cac2020/p/11579291.html
Copyright © 2011-2022 走看看