说明:使用类的方式编写程序启动脚本(memcached)
1 import time 2 import os 3 from subprocess import Popen,PIPE 4 5 class Process(object): 6 'mamcached rc scripts' 7 def __init__(self,name,program,args,workdir): 8 self.name = name 9 self.program = program 10 self.args = args 11 self.workdir = workdir 12 self._init() 13 14 def _init(self): 15 '''/var/tmp/memcached''' 16 if not os.path.exists(self.workdir): 17 os.mkdir(self.workdir) 18 os.chdir(self.workdir) 19 20 def _pidfile(self): 21 '''/var/tmp/memcached/memcached.pid''' 22 return os.path.join(self.workdir,'%s.pid' % self.name) 23 24 def _writepid(self): 25 if self.pid: 26 with open(self._pidfile(),'w') as fd: 27 fd.write(str(self.pid)) 28 29 def _getpid(self): 30 p = Popen(['pidof','memcached'],stdout=PIPE) 31 pid = p.stdout.read().strip('\n') 32 if pid: 33 return int(pid) 34 return None 35 36 def start(self): 37 cmd = self.program + ' ' + self.args 38 p = Popen(cmd,stdout=PIPE,shell=True) 39 self.pid = p.pid 40 self._writepid() 41 print('%s start Successful ' % self.name) 42 43 def stop(self): 44 result = self._getpid() 45 if result: 46 os.kill(result,15) 47 if os.path.exists(self._pidfile()): 48 os.remove(self._pidfile()) 49 print('The %s are stoped !' % self.name) 50 51 def restart(self): 52 self.stop() 53 time.sleep(1) 54 self.start() 55 56 def status(self): 57 pid = self._getpid() 58 if pid: 59 print('The %s is running , The pid is %s' % (self.name,pid)) 60 else: 61 print('The %s is not running!' % self.name) 62 63 def help(self): 64 print('Usage: %s {start|restart|status|stop}' % __file__ ) 65 66 def main(): 67 name = 'memcached' 68 program = '/usr/bin/memcached' 69 args = '-u nobody -p 11211 -c 1024 -m 64 ' 70 wd = '/var/tmp/memcached' 71 pm = Process(name,program,args,wd) 72 try: 73 cmd = sys.argv[1] 74 except IndexError as e: 75 sys.exit('Option Error') 76 if cmd == 'start': 77 pm.start() 78 elif cmd == 'stop': 79 pm.stop() 80 elif cmd == 'restart': 81 pm.restart() 82 elif cmd == 'status': 83 pm.status() 84 else: 85 pm.help() 86 87 88 if __name__ == '__main__': 89 main()