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 相关文章推荐
python抓取最新博客内容并生成Rss
May 17 Python
python3读取MySQL-Front的MYSQL密码
May 03 Python
Python部署web开发程序的几种方法
May 05 Python
浅谈python for循环的巧妙运用(迭代、列表生成式)
Sep 26 Python
PyCharm鼠标右键不显示Run unittest的解决方法
Nov 30 Python
使用Python中的reduce()函数求积的实例
Jun 28 Python
Python CVXOPT模块安装及使用解析
Aug 01 Python
Python简易计算器制作方法代码详解
Oct 31 Python
Python 基于wxpy库实现微信添加好友功能(简洁)
Nov 29 Python
Python模块 _winreg操作注册表
Feb 05 Python
python如何写出表白程序
Jun 01 Python
Python安装第三方库攻略(pip和Anaconda)
Oct 15 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
PHP+javascript液晶时钟
2006/10/09 PHP
PHP 读取Postgresql中的数组
2013/04/14 PHP
微信营销平台系统?刮刮乐的开发
2014/06/10 PHP
php实现paypal 授权登录
2015/05/28 PHP
由prototype_1.3.1进入javascript殿堂-类的初探
2006/11/06 Javascript
javascript contains和compareDocumentPosition 方法来确定是否HTML节点间的关系
2010/02/04 Javascript
jQuery AJAX 调用WebService实现代码
2010/03/24 Javascript
利用函数的惰性载入提高javascript代码执行效率
2014/05/05 Javascript
js分页工具实例
2015/01/28 Javascript
JS实现自适应高度表单文本框的方法
2015/02/25 Javascript
js完美实现@提到好友特效(兼容各大浏览器)
2015/03/16 Javascript
JS实现简洁、全兼容的拖动层实例
2015/05/13 Javascript
js显示当前日期时间和星期几
2015/10/22 Javascript
jQuery prototype冲突的2种解决方法(附demo示例下载)
2016/01/21 Javascript
实例详解ECMAScript5中新增的Array方法
2016/04/05 Javascript
javascript计算渐变颜色的实例
2017/09/22 Javascript
three.js实现3D模型展示的示例代码
2017/12/31 Javascript
vue 修改 data 数据问题并实时显示的方法
2018/08/27 Javascript
vue项目首屏打开速度慢的解决方法
2019/03/31 Javascript
vue-drag-chart 拖动/缩放图表组件的实例代码
2020/04/10 Javascript
JavaScript中的this妙用实例分析
2020/05/09 Javascript
在vue中通过render函数给子组件设置ref操作
2020/11/17 Vue.js
利用python爬取散文网的文章实例教程
2017/06/18 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
2020/06/23 Python
Python两台电脑实现TCP通信的方法示例
2019/05/06 Python
如何使用python进行pdf文件分割
2019/11/11 Python
python实现视频读取和转化图片
2019/12/10 Python
opencv python 图片读取与显示图片窗口未响应问题的解决
2020/04/24 Python
Python代码执行时间测量模块timeit用法解析
2020/07/01 Python
python 用Matplotlib作图中有多个Y轴
2020/11/28 Python
使用HTML5 Canvas API绘制弧线的教程
2016/03/22 HTML / CSS
HTML5 source标签:媒介元素定义媒介资源
2018/01/29 HTML / CSS
德国狗狗用品在线商店:Schecker
2017/03/17 全球购物
小学生法制教育心得体会
2016/01/14 职场文书
​(迎国庆)作文之我爱我的祖国
2019/09/19 职场文书
交互式可视化js库gojs使用介绍及技巧
2022/02/18 Javascript