python判斷自身是否正在運行的方法
更新時間:2019年08月08日 10:24:45 作者:septwolves2015
今天小編就為大家分享一篇python判斷自身是否正在運行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
如下所示:
# 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: write_pid() time.sleep(20) if __name__ == "__main__": run()
實現(xiàn)思路:
1)用os.getpid()獲取當前程序運行PID,將PID存入文件中
2)用psutil模塊獲取當前系統(tǒng)所有正在運行的pid
3)讀取之前存入的PID,判斷該PID是否在系統(tǒng)PID中
4)如果文件中的PID在系統(tǒng)PID中,則退出程序,否則存入新的PID,運行程序。
以上這篇python判斷自身是否正在運行的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MacOS安裝python報錯"zsh:?command?not?found:python"的
這篇文章主要給大家介紹了關于MacOS安裝python報錯"zsh:?command?not?found:python"的解決方法,文中將解決的辦法介紹的非常詳細,需要的朋友可以參考下2023-02-02使用Pandas?實現(xiàn)MySQL日期函數(shù)的解決方法
這篇文章主要介紹了用Pandas?實現(xiàn)MySQL日期函數(shù)的效果,Python是很靈活的語言,達成同一個目標或有多種途徑,我提供的只是其中一種解決方法,需要的朋友可以參考下2023-02-02Python tkinter實現(xiàn)簡單加法計算器代碼實例
這篇文章主要介紹了Python tkinter實現(xiàn)簡單加法計算器代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05