首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用KeyboardInterrupt停止python脚本

使用KeyboardInterrupt停止python脚本
EN

Stack Overflow用户
提问于 2018-09-02 10:53:10
回答 1查看 56关注 0票数 0

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

我使用的是python线程,它运行两个函数coinPulser和coinPulserDone。

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-02 11:07:53

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

代码语言:javascript
复制
while True:
    time.sleep(1)

在你的the行应该可以做这个之前。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52133614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档