最近一个项目中用gulp-watch不能满足需求,于是想到了用Python来解决问题。在安装了MacFSEvents模块后,写了下面一个小程序。
#!/usr/bin/env python2 #-*- coding: utf-8 -*- import os,sys,signal from fsevents import Observer from fsevents import Stream def callback(FileEvent): # attributes of FileEvent:mask, cookie and name. # mask: 512-delete;256-create;2-changed if FileEvent.name.endswith("index.html") and FileEvent.mask == 256: print "site rebuild. redeploy extra assets" os.system("gulp") elif FileEvent.name.endswith(".scss") and FileEvent.mask == 2: print "scss changed! compile and redeploy extra assets" os.system("gulp sass") if __name__ == '__main__': observer = Observer() stream = Stream(callback, ".", file_events=True) observer.schedule(stream) observer.start() #按Control+\强制结束
但是运行时发现只能用Control+\强杀进程,而不能用Control+C结束。
经google搜索及自行研究结果,得到下面这段程序。用fork子进程的方法,使得进程响应Control+C 退出。
1 #!/usr/bin/env python2 2 #-*- coding: utf-8 -*- 3 4 import os,sys,signal 5 from fsevents import Observer 6 from fsevents import Stream 7 8 def callback(FileEvent): 9 # attributes of FileEvent:mask, cookie and name. 10 # mask: 512-delete;256-create;2-changed;... 11 if FileEvent.name.endswith("index.html") and FileEvent.mask == 256: 12 print "site rebuild. redeploy extra assets" 13 os.system("gulp") 14 elif FileEvent.name.endswith(".scss") and FileEvent.mask == 2: 15 print "scss changed! compile and redeploy extra assets" 16 os.system("gulp sass") 17 18 def child(): 19 observer = Observer() 20 stream = Stream(callback, ".", file_events=True) 21 observer.schedule(stream) 22 observer.start() 23 24 class Watcher: 25 """
26 创建一个做苦工的子进程。然后父进程等待KeyboardInterrupt并杀掉子进程。
27
28 """ 29 30 def __init__(self): 31 self.child = os.fork() 32 if self.child == 0: 33 child() 34 else: 35 self.watch() 36 37 def watch(self): 38 try: 39 os.wait() 40 except KeyboardInterrupt: 41 #捕获 Control+C,杀掉子进程 42 print 'KEYBOARDINTERRUPT\n' 43 self.kill() 44 sys.exit() 45 46 def kill(self): 47 try: 48 os.kill(self.child, signal.SIGKILL) 49 except OSError: pass 50 51 52 if __name__ == '__main__': 53 Watcher()