开发者

How to exit from a Python program using MacFSEvents using Ctrl-C

开发者 https://www.devze.com 2023-02-23 01:20 出处:网络
I\'m using MacFSEvents, a Python library that 开发者_JAVA百科monitors a directory for changes on Mac OS X, like so:

I'm using MacFSEvents, a Python library that 开发者_JAVA百科monitors a directory for changes on Mac OS X, like so:

# from http://pypi.python.org/packages/source/M/MacFSEvents/
from fsevents import Observer
from fsevents import Stream
observer = Observer()

def callback(event):
    print event.name

stream = Stream(callback, '.', file_events=True)
observer.schedule(stream)
observer.start()

When I run this script in the Terminal, hitting Ctrl-C doesn't exit the program -- the only way I can find to kill it is with 'kill' in a separate window, or with Activity Monitor, etc.

Any ideas on how to make such a program killable by Ctrl-C?


The answer, by the way, is the little known Ctrl-\, which sends SIGQUIT to the process, and will quit it no matter how hung.


An alternative is to look for KeyboardInterrupt and stop the observer manually (as an alternative to observer.run()):

def better_run(observer):
   try:
      observer.start()
      while True:      # instead of this infinite loop, you can do
         pass          # whatever processing you wanted
   except KeyboardInterrupt:
      observer.stop()
0

精彩评论

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