将函数放在线程中,然后等待线程完成。
除非使用特殊的C api,否则无法中断Python线程。
import timefrom threading import Threaddef noInterrupt(): for i in xrange(4): print i time.sleep(1)a = Thread(target=noInterrupt)a.start()a.join()print "done"0123Traceback (most recent call last): File "C:UsersAdminDesktoptest.py", line 11, in <module> a.join() File "C:Python26libthreading.py", line 634, in join self.__block.wait() File "C:Python26libthreading.py", line 237, in wait waiter.acquire()KeyboardInterrupt
看看如何将中断推迟到线程完成为止?
在这里它适合您的使用:
import timefrom threading import Threaddef noInterrupt(path, obj): try: file = open(path, 'w') dump(obj, file) finally: file.close()a = Thread(target=noInterrupt, args=(path,obj))a.start()a.join()



