python判断自身是否正在运行的方法

yipeiwu_com5年前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()

实现思路:

1)用os.getpid()获取当前程序运行PID,将PID存入文件中

2)用psutil模块获取当前系统所有正在运行的pid

3)读取之前存入的PID,判断该PID是否在系统PID中

4)如果文件中的PID在系统PID中,则退出程序,否则存入新的PID,运行程序。

以上这篇python判断自身是否正在运行的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

wxPython中listbox用法实例详解

本文实例讲述了wxPython中listbox用法。分享给大家供大家参考。具体如下: # load a listbox with names, select a name and d...

python实现控制电脑鼠标和键盘,登录QQ的方法示例

本文实例讲述了python实现控制电脑鼠标和键盘,登录QQ的方法。分享给大家供大家参考,具体如下: import os from pynput.mouse import Button...

跟老齐学Python之类的细节

这几天和几个朋友以各种途径讨论过OOP的相关问题,他们是:令狐虫、Frank、晋剑、小冯 大家对OOP有不同看法,所谓工程派和学院派看法不一致。从应用的角度看,工程派的观点是值得推荐的,...

python中pip的安装与使用教程

python中pip的安装与使用教程

在安装pip前,请确认win系统中已经安装好了python,和easy_install工具,如果系统安装成功,easy_install在目录python的安装盘(如C盘):\Python...

python打开网页和暂停实例

本文实例讲述了python打开网页和暂停的方法。分享给大家供大家参考。 具体实现代码如下: import webbrowser import os webbrowser.open_...