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

相关文章

Python OpenCV实现视频分帧

本文实例为大家分享了Python OpenCV实现视频分帧的具体代码,供大家参考,具体内容如下 # coding=utf-8 import os import cv2 video...

Python的Django REST框架中的序列化及请求和返回

序列化Serialization 1. 设置一个新的环境 在我们开始之前, 我们首先使用virtualenv要创建一个新的虚拟环境,以使我们的配置和我们的其他项目配置彻底分开。 $m...

linux系统使用python监测网络接口获取网络的输入输出

linux系统使用python监测网络接口获取网络的输入输出

net.py 获取网络接口的输入和输出 复制代码 代码如下:#!/usr/bin/env Pythonimport timeimport sys if len(sys.argv) >...

Python 利用高德地图api实现经纬度与地址的批量转换

我们都知道,可以使用高德地图api实现经纬度与地址的转换。那么,当我们有很多个地址与经纬度,需要批量转换的时候,应该怎么办呢? 在这里,选用高德Web服务的API,其中的地址/逆地址编码...

Python算法的时间复杂度和空间复杂度(实例解析)

算法复杂度分为时间复杂度和空间复杂度。 其作用: 时间复杂度是指执行算法所需要的计算工作量; 而空间复杂度是指执行这个算法所需要的内存空间。 (算法的复杂性体现在运行该算法时的计算...