python判断自身是否正在运行的方法
作者:septwolves2015 时间:2022-07-30 02:34:44
如下所示:
# 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,运行程序。
来源:https://blog.csdn.net/septwolves2015/article/details/78633064
标签:python,判断,自身,运行


猜你喜欢
Python flask与fastapi性能测试方法介绍
2022-12-07 00:10:17
Python实现的百度站长自动URL提交小工具
2023-08-24 10:36:31
Scala项目构建工具sbt和IntelliJ IDEA环境配置详解
2023-06-09 10:16:03

js multiple全选与取消全选实现代码
2024-04-28 10:19:36
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
2021-09-14 17:03:46

Go实现双向链表的示例代码
2024-03-13 04:11:45

php函数重载的替代方法--伪重载详解
2023-11-18 10:24:06
python中sys模块的介绍与实例
2022-11-29 12:37:51
Python爬虫实战之网易云音乐加密解析附源码
2022-08-28 04:03:58

Python自动化测试之登录脚本的实现
2022-11-18 07:30:50

什么是XML?
2007-10-29 12:53:00
基于pandas向csv添加新的行和列
2021-11-29 02:28:56

Microsoft SQL Server 2000安装问题集锦
2008-12-10 14:26:00
python绘制字符画视频的示例代码
2023-11-09 16:21:46

python计算方程式根的方法
2023-08-09 09:54:47
matplotlib 输出保存指定尺寸的图片方法
2021-09-06 11:29:12
vue2.0中set添加属性后视图不能更新的解决办法
2024-04-28 10:55:18

一个mysql死锁场景实例分析
2024-01-16 21:59:47

与MSSQL对比学习MYSQL的心得(四)--BLOB数据类型
2024-01-20 12:32:53
Windows系统下实现pycharm运行.sh文件(本地运行和打开服务器终端)
2021-03-04 23:53:45
