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

yipeiwu_com6年前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设计】。

相关文章

pyqt5 实现 下拉菜单 + 打开文件的示例代码

如下所示: # -*- coding: utf-8 -*- import sys import os from PyQt5 import QtCore, QtGui, QtWidge...

Python中字符串String的基本内置函数与过滤字符模块函数的基本用法

首先我们要明白在python中当字符编码为:UTF-8时,中文在字符串中的占位为3个字节,其余字符为一个字节 下面就直接介绍几种python中字符串常用的几种字符串内置函数(本文中牵扯到...

python通过wxPython打开一个音频文件并播放的方法

本文实例讲述了python通过wxPython打开一个音频文件并播放的方法。分享给大家供大家参考。具体如下: 这段代码片段使用wx.lib.filebrowsebutton.FileBr...

python开发之anaconda以及win7下安装gensim的方法

一、推荐安装Anaconda 官方介绍:Anaconda is a completely free Python distribution (including for commerci...

跟老齐学Python之正规地说一句话

小孩子刚刚开始学说话的时候,常常是一个字一个字地开始学,比如学说“饺子”,对他/她来讲,似乎有点难度,大人也聪明,于是就简化了,用“饺饺”来代替,其实就是让孩子学会一个字就能表达。当然,...