按Ctrl + C后如何在程序停止之前让Python完成作业?

时间:2017-05-30 12:33:04

标签: python python-3.x loops

我有4个这样的无限循环:

list1 = []
while 1:
    try:
        # job1
        a = B()
        # job2
        c = a.accd()
        # job3
        d = len(c)
        # job4
        list1.append(d)
    except KeyboardInterrupt:
        # save list1 into database(took long time)
        break

按Ctrl + C后,我无法确保它完成所有4个作业然后停止。

这似乎在睡觉时起作用,但它有睡眠延迟。

list1 = []
while 1:
    try:
        # job1
        a = B()
        # job2
        c = a.accd()
        # job3
        d = len(c)
        # job4
        list1.append(d)
    except aaddcdcd:
        # some code here
    finally:
        try:
            time.sleep(3) # if I press Ctrl + C here it works perfectly
        except: KeyboardInterrupt:
            # save list1 into database(took long time)
            break

是否有可能在我按某个键的任何时候,它会执行此循环中的所有作业,更新数据库然后停止。

1 个答案:

答案 0 :(得分:2)

好的,我有两个答案。

第一个回答

def jobOne():
    pass
def jobTwo():
    pass
def jobThree():
    pass
def jobFour():
    pass

interrupted    = False
finished       = False
jobs           = [jobOne, jobTwo, jobThree, jobFour]
jobsCarriedOut = [0] * len(jobs)
currentJob     = 0

while (not finished or not interrupted):
    try:
        jobs[currentJob]()
        jobsCarriedOut[currentJob] += 1

        currentJob += 1

        if currentJob == len(jobs):
            currentJob, finished = 0, True
        else:
            finished = False
    except KeyboardInterrupt:
        interrupted = True

print(jobsCarriedOut)

一旦KeyboardInterrupt被触发并且所有工作都已完成,这件作品将退出。

第二个回答

我只是用谷歌搜索禁用键盘中断python 并找到了这个How can I override the keyboard interrupt? (Python)并提出了这个稍有不同的代码。

import signal

def signal_handler(signal, frame):
    global interrupted
    interrupted = True

def jobOne():
    pass
def jobTwo():
    pass
def jobThree():
    pass
def jobFour():
    pass

interrupted    = False
finished       = False
jobs           = [jobOne, jobTwo, jobThree, jobFour]
jobsCarriedOut = [0] * len(jobs)
currentJob     = 0

signal.signal(signal.SIGINT, signal_handler)

while (not finished or not interrupted):
    jobs[currentJob]()
    jobsCarriedOut[currentJob] += 1
    currentJob += 1
    if currentJob == len(jobs):
        currentJob, finished = 0, True
    else:
        finished = False

print(jobsCarriedOut)

我从未使用过信号库(或者甚至没有使用过它),所以这里是documentation

编辑我从未使用全局变量,因此我的使用可能有误。

EDIT TWO 由于未在每一步捕获错误,第一个示例仅占80%的时间