Questions tagged «keyboardinterrupt»

10
键盘中断与python的多处理池
如何使用python的多处理池处理KeyboardInterrupt事件?这是一个简单的示例: from multiprocessing import Pool from time import sleep from sys import exit def slowly_square(i): sleep(1) return i*i def go(): pool = Pool(8) try: results = pool.map(slowly_square, range(40)) except KeyboardInterrupt: # **** THIS PART NEVER EXECUTES. **** pool.terminate() print "You cancelled the program!" sys.exit(1) print "\nFinally, here are the results: …


2
在程序关闭期间在Python中捕获KeyboardInterrupt
我正在用Python编写一个命令行实用程序,由于它是生产代码,因此应该能够干净关闭,而不会在屏幕上倾倒一堆东西(错误代码,堆栈跟踪等)。这意味着我需要捕获键盘中断。 我试过使用try catch块,如: if __name__ == '__main__': try: main() except KeyboardInterrupt: print 'Interrupted' sys.exit(0) 并捕获信号本身(如本文中所示): import signal import sys def sigint_handler(signal, frame): print 'Interrupted' sys.exit(0) signal.signal(signal.SIGINT, sigint_handler) 两种方法在正常运行期间似乎都能很好地工作。但是,如果在应用程序末尾的清除代码期间发生中断,则Python似乎总是在屏幕上打印一些内容。捕捉中断给 ^CInterrupted Exception KeyboardInterrupt in <bound method MyClass.__del__ of <path.to.MyClass object at 0x802852b90>> ignored 而处理信号给 ^CInterrupted Exception SystemExit: 0 in <Finalize object, dead> …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.