运维开发网

12.7python笔记(3.5-3.8)

运维开发网 https://www.qedev.com 2020-03-11 17:46 出处:51CTO 作者:wuyinchen
3.5rc脚本(类的定义与脚本的结构)用python写一个启动脚本#!/usr/bin/pythonimportsysimportosfromsubprocessimportPopen,PIPEclassProcess(object):'''memcachedrcscript'''definit(self,name,program,args,work

3.5 rc脚本(类的定义与脚本的结构)

用python写一个 启动脚本

#!/usr/bin/python

import sys

import os

from subprocess import Popen, PIPE

class Process(object):

'''memcached rc script'''

def init(self,name,program,args,workdir):

self.name = name

self.program = program

self.args = args

self.workdir = workdir

  def _pidFile(self):
       '''/var/tmp/memcached/memcached.pid'''
       return os.path.join(self.workdir, "%s.pid" % self.name)
  def _writhPid(self):
       if self.pid:
          with open(self._pidFile(),'w') as fd:
               fd.write(str(self.pid))

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

  def start(self):
      self._init()
      cmd = self.program  + ' ' + self.args
      p = Popen(cmd, stdout=PIPE, shell=True)
      self.pid = p.pid
      self._writhPid()
      print "%s start Sucessful" % self.name

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

  def stop(self):
      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):
      self.stop()
      self.start()

  def status(self):
      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|status|restart}" % __file__

def main():

name = 'memcached'

prog = '/usr/bin/memcached'

args = '-u nobody -p 11211 -c 1024 -m 64'

wd = '/var/tmp/memcached'

pm = Process(name=name,program=prog,args=args,workdir = wd)

  try:
        cmd = sys.argv[1]
  except IndexError, e:
        print "Option error"
        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()

0

精彩评论

暂无评论...
验证码 换一张
取 消