【pythonラーニングケース】pythonは、自身が実行中であるか否かを判断する

4647 ワード

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()

 
転載先:https://www.cnblogs.com/cac2020/p/11579291.html