欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-07-20 08:53:40|栏目: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 selenium爬虫实现定时任务过程解析

栏    目:Python代码

下一篇:python中栈的原理及实现方法示例

本文标题:python判断自身是否正在运行的方法

本文地址:http://www.codeinn.net/misctech/159440.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有