大神指導做品:python
#!/usr/bin/python
#coding:utf8
from functools import wraps
from time import sleep
import os
RESTART='pm2 restart ios-push'
# coroutine 先要用 next 語句調用一次
def coroutine(fn):
@wraps(fn)
def wrapper(*args,**kwargs):
ret=fn(*args,**kwargs)
next(ret)
return ret
return wrapper
def follow(file,target):
'''
相似 Unix 的 tail -f, 可是接受一個 target, 有新的數據,交給 target 處理
'''
file.seek(0,2)# 直接到文件的最後一行,相似 tail -f -n 0
while True:
line=file.readline()#讀取行
if not line:
sleep(0.5)# 若是是空行,直接 sleep 0.5s,而後 continue
continue
target.send(line)# 若是有新數據,則交給 target 處理
def action():
if os.system(RESTART) == 0:
print('ios-push restart success!')
#print('restart')
@coroutine
def grep(pattern):
'''
grep 是一個 coroutine,接受一個 pattern 參數,須要從外部 send 數據 ,若是接受的數據匹配 pattern 經過了,則調用action函數
'''
while True:
line = yield
if pattern in line:
action()
if __name__ == '__main__':
follow(open('error.log','r'),grep('MaxListenersExceededWarn'))
ios