使用KeyboardInterrupt停止python脚本

时间:2018-09-02 02:53:10

标签: python python-3.x

嗨,为什么我的KeyboardInterrupt:当我按下控件c或控件x时没有停止我的程序?这是我当前的代码。

我正在使用运行2个功能coinPulser和coinPulserDone的python线程。

import threading
import time

lock = threading.Lock()
counter = 0
input = 3

def coinPulser ():
    global counter
    global input
    lock.acquire()
    try:
        while counter < input:
            counter+=1
            time.sleep(.1)
            if counter in [1,3,5]:
                print(counter)
        return counter
    finally:
        lock.release()

def coinPulserDone ():
    while True:
        print(coinPulser())


try:
    coinpulser = threading.Thread(target = coinPulser)
    coinpulser.start()
    coinpulserdone = threading.Thread(target = coinPulserDone)
    coinpulserdone.start()
except KeyboardInterrupt:
    coinpulser.stop()
    coinpulserdone.stop()
    print('Thread Stops')

1 个答案:

答案 0 :(得分:0)

我怀疑问题是您的代码在按Cntr-C之前退出了try / except块。您需要添加某种形式的循环,将其保留在该块中。一个简单的循环,例如

while True:
    time.sleep(1)

在您的except行之前应该可以解决问题。