写一个python的服务监控程序

前言:

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上执行非常easy:

$ python service_mgr.py

Windows上以后台进程执行:

> start pythonw service_mgr.py

代码中须要改动:

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

python 程序块 挂掉的服务_写一个python的服务监控程序相关推荐

  1. python写一个服务_写一个Python的windows服务

    1. 安装pywin32和pyinstaller pip install pywin32 pip install pyinstaller 2.写一个服务Demo # -*- coding: utf-8 ...

  2. python监控某个程序_写一个python的服务监控程序

    写一个python的服务监控程序 前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4. 到python网站下载源代码,解压到Redhat上, ...

  3. python的程序入口地址_第一个Python程序

    在写代码之前,请千万不要用"复制"-"粘贴"把代码从页面粘贴到你自己的电脑上.写程序也讲究一个感觉,你需要一个字母一个字母地把代码自己敲进去,在敲代码的过程中, ...

  4. python小欢喜(一)写一个python程序如此简单

    python是一门有趣又有用的语言. 如何才能学会python呢? 跟我嗨起来吧,我们要用最简单的方法,最快的速度学会python. 相信我,凡事都有捷径,学python也不例外. 咱们需要做点什么准 ...

  5. 苹果笔记本python开发第一个程序_第一个Python程序【文章来自老男孩】

    首先我们打开python 交互式解释器, 执行如下命令: Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on ...

  6. python hello world程序代码_第一个Python程序——hello world

    helloWorld 一直都是每一门语言经典的第一课, 就是使用那一种语言输出 HelloWorld 的字符串 下面 ,就用 python.在终端里面输出 HelloWorld 代码非常简单,只需要一 ...

  7. python类的成员函数_注入一个python类成员函数

    你在这里要做的是Child2.foo用self不是a的方法调用未绑定的方法Child2. 这是非法的,Python 2将检测到并提出一个TypeError解释错误的地方:TypeError: unbo ...

  8. python写一个完整的小程序_写一个python小程序

    在windows环境下进行操作 window+R 输入cmd  创建一个文件夹 mkdir pytxt 创建一个py文件 py.py  用notepad或者记事本等工具进行编辑 或 首先声明pytho ...

  9. python爬虫下载电影百度文档_写一个python 爬虫爬取百度电影并存入mysql中

    目标是利用python爬取百度搜索的电影 在类型 地区 年代各个标签下 电影的名字 评分 和图片连接 以及 电影连接 首先我们先在mysql中建表 create table liubo4( id in ...

最新文章

  1. 求解单源最短路径的几种算法
  2. O365(世纪互联)SharePoint 之站点个性化
  3. 大型网站架构系列:消息队列
  4. 免费的SEO工具软件大全
  5. 解决Maven报Plugin execution not covered by lifecycle configuration
  6. pjsip for Android的编译
  7. (11)python里面while到底有多少知识点
  8. 怎样安装两个tomcat,怎样配置
  9. 7-40 最大的数 (10 分)
  10. 该拒绝MSN Messager了
  11. win7系统修复工具_系统哥教你如何修复win7启动引导的方法
  12. YEDDA使用方法 命名实体识别
  13. Word删除表格后的空白页
  14. 根据录入的计算公式计算_炒股还需工匠精神:请笑纳30个财务分析指标和计算方式,上市公司财务分析必备,速速珍藏...
  15. 【机器学习】LifeLong Learning(终身学习)介绍
  16. 深入浅出C++ ——初识C++
  17. [学习笔记]模拟退火
  18. [AGC001E]BBQ Hard
  19. HTML 通过GIF实现loading动画(非进度条版)。
  20. 电商平台投诉,都适用哪些场景

热门文章

  1. 手机服务器密码在什么位置,手机远程云服务器登录密码是什么
  2. box怎么用 latency_box-sizing使用场景
  3. ubuntu 串口 树莓派_linux系统(ubuntu)烧录安装树莓派及远程连接树莓派
  4. # 异运算_人教版六年级数学下册第29课数的运算(P7680)图文视频辅导
  5. turtle fillcolor_超详细!turtle库的使用
  6. 光感是什么_华强北airpods2洛达1536U-001到底升级了什么?
  7. pythongui界面实例_wxPython:python首选的GUI库实例分享(5)
  8. .Net 指针使用以及在栈上创建引用对象
  9. 彻底弄懂jsonp原理及实现方法
  10. 精巧好用的DelayQueue