实例:用类来写一个 memcached 启动脚本

[root@localhost ~]$ yum install -y memcached
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
from subprocess import Popen, PIPE

class Process(object):

    def __init__(self, name, program, args, workdir):
        self.name = name
        self.program = program
        self.args = args
        self.workdir = workdir

    def _init(self):
        '''创建/var/tmp/memcached目录'''
        if not os.path.exists(self.workdir):
            os.mkdir(self.workdir)
            os.chdir(self.workdir)

    def _pidFile(self):
        '''返回/var/tmp/memcached/memcached.pid路径'''
        return os.path.join(self.workdir, "%s.pid" % self.name)

    def _writePid(self):
        '''把pid写入到pid文件'''
        if self.pid:
            with open(self._pidFile(), 'w') as fd:
                fd.write(str(self.pid))

    def _getPid(self):
        '''获取pid'''
        p = Popen(['pidof', self.name], stdout=PIPE)
        pid = p.stdout.read().strip()
        return pid

    def start(self):
        '''定义start动作'''
        self._init()
        cmd = self.program + ' ' + self.args
        p = Popen(cmd, stdout=PIPE, shell=True)
        self.pid = p.pid
        self._writePid()
        print("%s start Successful" % self.name)

    def stop(self):
        '''定义stop动作'''
        pid = self._getPid()
        if pid:
            os.kill(int(pid), 15)
            if os.path.exists(self._pidFile()):
                os.remove(self._pidFile())
            print("%s is stopped" % self.name)
        
    def restart(self):
        '''定义restart动作'''
        self.stop()
        self.start()

    def status(self):
        '''定义status动作'''
        pid = self._getPid()
        if pid:
            print("%s is already running..." % self.name)
        else:
            print("%s is not running..." % self.name)

    def help(self):
        '''定义帮助信息'''
        print("Usage: %s {start|stop|restart|status}" % __file__)

def main():
    name = 'memcached'
    program = '/usr/bin/memcached'
    args = '-u nobody -p 11211 -C 1024 -m 64'
    workdir = '/var/tmp/memcached'
    pm = Process(name = name, program = program, args = args, workdir = workdir)

    try:
        cmd = sys.argv[1]
    except IndexError, e:
        pm.help()
        sys.exit()

    if cmd == 'start':
        pm.start()
    elif cmd == 'stop':
        pm.stop()
    elif cmd == 'restart':
        pm.restart()
    elif cmd == 'status':
        pm.status()
    else:
        pm.help()

if __name__ == '__main__':
    main()

 

 

 

 

 

 

    

    

posted @ 2019-01-17 07:33  孔雀东南飞  阅读(195)  评论(0编辑  收藏  举报