Python写的服务监控程序实例


Posted in Python onJanuary 31, 2015

前言:

Redhat下安装Python2.7

rhel6.4自带的是2.6, 发现有的机器是python2.4。 到python网站下载源代码,解压到Redhat上,然后运行下面的命令:

# ./configure --prefix=/usr/local/python27

# make

# make install

这样安装之后默认不会启用Python2.7,需要使用/usr/local/python27/bin/python2.7调用新版本的python。

而下面的安装方式会直接接管现有的python

# ./configure

# make

# make install

开始:

服务子进程被监控主进程创建并监控,当子进程异常关闭,主进程可以再次启动之。使用了python的subprocess模块。就这个简单的代码,居然互联网上没有现成可用的例子。没办法,我写好了贡献出来吧。

首先是主进程代码:service_mgr.py

#!/usr/bin/python  

#-*- coding: UTF-8 -*-  

# cheungmine  

# stdin、stdout和stderr分别表示子程序的标准输入、标准输出和标准错误。  

#   

# 可选的值有:  

#   subprocess.PIPE - 表示需要创建一个新的管道.  

#   一个有效的文件描述符(其实是个正整数)  

#   一个文件对象  

#   None - 不会做任何重定向工作,子进程的文件描述符会继承父进程的.  

#   

# stderr的值还可以是STDOUT, 表示子进程的标准错误也输出到标准输出.  

#   

# subprocess.PIPE  

# 一个可以被用于Popen的stdin、stdout和stderr 3个参数的特输值,表示需要创建一个新的管道.  

#   

# subprocess.STDOUT  

# 一个可以被用于Popen的stderr参数的特输值,表示子程序的标准错误汇合到标准输出.  

################################################################################  

import os  

import sys  

import getopt  

  

import time  

import datetime  

  

import codecs  

  

import optparse  

import ConfigParser  

  

import signal  

import subprocess  

import select  

  

# logging  

# require python2.6.6 and later  

import logging    

from logging.handlers import RotatingFileHandler  

  

## log settings: SHOULD BE CONFIGURED BY config  

LOG_PATH_FILE = "./my_service_mgr.log"  

LOG_MODE = 'a'  

LOG_MAX_SIZE = 4*1024*1024 # 4M per file  

LOG_MAX_FILES = 4          # 4 Files: my_service_mgr.log.1, printmy_service_mgrlog.2, ...    

LOG_LEVEL = logging.DEBUG    

  

LOG_FORMAT = "%(asctime)s %(levelname)-10s[%(filename)s:%(lineno)d(%(funcName)s)] %(message)s"    

  

handler = RotatingFileHandler(LOG_PATH_FILE, LOG_MODE, LOG_MAX_SIZE, LOG_MAX_FILES)  

formatter = logging.Formatter(LOG_FORMAT)  

handler.setFormatter(formatter)  

  

Logger = logging.getLogger()  

Logger.setLevel(LOG_LEVEL)  

Logger.addHandler(handler)   

  

# color output  

#  

pid = os.getpid()   

  

def print_error(s):  

    print '\033[31m[%d: ERROR] %s\033[31;m' % (pid, s)  

  

def print_info(s):  

    print '\033[32m[%d: INFO] %s\033[32;m' % (pid, s)  

  

def print_warning(s):  

    print '\033[33m[%d: WARNING] %s\033[33;m' % (pid, s)  

  

  

def start_child_proc(command, merged):  

    try:  

        if command is None:  

            raise OSError, "Invalid command"  

  

        child = None  

  

        if merged is True:  

            # merge stdout and stderr  

            child = subprocess.Popen(command,  

                stderr=subprocess.STDOUT, # 表示子进程的标准错误也输出到标准输出  

                stdout=subprocess.PIPE    # 表示需要创建一个新的管道  

            )  

        else:  

            # DO NOT merge stdout and stderr  

            child = subprocess.Popen(command,  

                stderr=subprocess.PIPE,  

                stdout=subprocess.PIPE)  

  

        return child  

  

    except subprocess.CalledProcessError:  

        pass # handle errors in the called executable  

    except OSError:  

        pass # executable not found  

  

    raise OSError, "Failed to run command!"  

  

  

def run_forever(command):  

    print_info("start child process with command: " + ' '.join(command))  

    Logger.info("start child process with command: " + ' '.join(command))  

  

    merged = False  

    child = start_child_proc(command, merged)  

  

    line = ''  

    errln = ''  

  

    failover = 0  

  

    while True:  

        while child.poll() != None:  

            failover = failover + 1  

            print_warning("child process shutdown with return code: " + str(child.returncode))             

            Logger.critical("child process shutdown with return code: " + str(child.returncode))  

  

            print_warning("restart child process again, times=%d" % failover)  

            Logger.info("restart child process again, times=%d" % failover)  

            child = start_child_proc(command, merged)  

  

        # read child process stdout and log it  

        ch = child.stdout.read(1)  

        if ch != '' and ch != '\n':  

            line += ch  

        if ch == '\n':  

            print_info(line)  

            line = ''  

  

        if merged is not True:  

            # read child process stderr and log it  

            ch = child.stderr.read(1)  

            if ch != '' and ch != '\n':  

                errln += ch  

            if ch == '\n':  

                Logger.info(errln)  

                print_error(errln)  

                errln = ''  

  

    Logger.exception("!!!should never run to this!!!")    

  

  

if __name__ == "__main__":  

    run_forever(["python", "./testpipe.py"]) 

然后是子进程代码:testpipe.py

#!/usr/bin/python  

#-*- coding: UTF-8 -*-  

# cheungmine  

# 模拟一个woker进程,10秒挂掉  

import os  

import sys  

  

import time  

import random  

  

cnt = 10  

  

while cnt >= 0:  

    time.sleep(0.5)  

    sys.stdout.write("OUT: %s\n" % str(random.randint(1, 100000)))  

    sys.stdout.flush()  

  

    time.sleep(0.5)  

    sys.stderr.write("ERR: %s\n" % str(random.randint(1, 100000)))  

    sys.stderr.flush()  

  

    #print str(cnt)  

    #sys.stdout.flush()  

    cnt = cnt - 1  

  

sys.exit(-1) 

Linux上运行很简单:

$ python service_mgr.py

Windows上以后台进程运行:
> start pythonw service_mgr.py

代码中需要修改:
run_forever(["python", "testpipe.py"]) 
Python 相关文章推荐
python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序
Jul 20 Python
python树莓派红外反射传感器
Jan 21 Python
用python实现英文字母和相应序数转换的方法
Sep 18 Python
用Python解数独的方法示例
Oct 24 Python
Django框架ORM数据库操作实例详解
Nov 07 Python
python实现局域网内实时通信代码
Dec 22 Python
如何写python的配置文件
Jun 07 Python
Python 整行读取文本方法并去掉readlines换行\n操作
Sep 03 Python
Python自动化xpath实现自动抢票抢货
Sep 19 Python
Django项目创建及管理实现流程详解
Oct 13 Python
linux系统下pip升级报错的解决方法
Jan 31 Python
Python中使用tkFileDialog实现文件选择、保存和路径选择
May 20 Python
用python 制作图片转pdf工具
Jan 30 #Python
Python是编译运行的验证方法
Jan 30 #Python
Python的类实例属性访问规则探讨
Jan 30 #Python
Python中的作用域规则详解
Jan 30 #Python
Python中使用Boolean操作符做真值测试实例
Jan 30 #Python
Python中的zip函数使用示例
Jan 29 #Python
Python的另外几种语言实现
Jan 29 #Python
You might like
Zend Guard一些常见问题解答
2008/09/11 PHP
fleaphp下不确定的多条件查询的巧妙解决方法
2008/09/11 PHP
PHP+jquery实时显示网站在线人数的方法
2015/01/04 PHP
yii2中使用Active Record模式的方法
2016/01/09 PHP
PHP实现的简单分页类及用法示例
2016/05/06 PHP
PHP与jquery实时显示网站在线人数实例详解
2016/12/02 PHP
php post json参数的传递和接收处理方法
2018/05/31 PHP
thinkPHP框架中layer.js的封装与使用方法示例
2019/01/18 PHP
JQuery 获取和设置Select选项的代码
2010/02/07 Javascript
jQuery 打造动态下滑菜单实现说明
2010/04/15 Javascript
页面加载完毕后滚动条自动滚动一定位置
2014/02/20 Javascript
用js的document.write输出的广告无阻塞加载的方法
2014/06/05 Javascript
jQuery自定义添加"$"与解决"$"冲突的方法
2015/01/19 Javascript
JavaScript中Function()函数的使用教程
2015/06/04 Javascript
Vue.js 2.0窥探之Virtual DOM到底是什么?
2017/02/10 Javascript
BootStrap Validator 根据条件在JS中添加或移除校验操作
2017/10/12 Javascript
详解nodejs 配置文件处理方案
2019/01/02 NodeJs
[00:43]魔廷新尊——痛苦女王至宝捆绑包
2020/06/12 DOTA
Python开发编码规范
2006/09/08 Python
Python基于动态规划算法解决01背包问题实例
2017/12/06 Python
用tensorflow实现弹性网络回归算法
2018/01/09 Python
快速了解Python开发中的cookie及简单代码示例
2018/01/17 Python
使用Python进行QQ批量登录的实例代码
2018/06/11 Python
django多个APP的urls设置方法(views重复问题解决)
2019/07/19 Python
对Tensorflow中tensorboard日志的生成与显示详解
2020/02/04 Python
Python如何使用paramiko模块连接linux
2020/03/18 Python
Python定时从Mysql提取数据存入Redis的实现
2020/05/03 Python
Keras使用ImageNet上预训练的模型方式
2020/05/23 Python
Python生成随机验证码代码实例解析
2020/06/09 Python
html5指南-7.geolocation结合google maps开发一个小的应用
2013/01/07 HTML / CSS
html5手机端页面可以向右滑动导致样式受影响的问题
2018/06/20 HTML / CSS
向国旗敬礼学生寄语大全
2014/09/30 职场文书
离婚协议书格式
2015/01/26 职场文书
幼儿园国庆节活动总结
2015/03/23 职场文书
高一数学教学反思
2016/02/18 职场文书
六年级作文之预言作文
2019/10/25 职场文书