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

标签 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 个作业然后停止。

这似乎在 sleep 时有效,但它有 sleep 延迟。

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

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

最佳答案

好的,我有两个答案给你。

第一个回答

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

编辑 我从未使用过全局变量,所以我的用法可能是错误的。

编辑二 第一个示例只有 80%~ 的时间有效,因为没有在每一步捕获错误

关于python - 按 Ctrl+C 后如何让 Python 在程序停止之前完成作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44262403/

相关文章:

python - 如果其中 1 列没有任何值,则隐藏 QTableWidget 中的行

python - 当我使用 scrapy 在 Python 中抓取数据时生成一个项目时,项目会返回到哪里?

python - Flask 显示 TypeError : send_from_directory() missing 1 required positional argument: 'path'

python - 如何从Windows上开发的Python脚本在Mac上创建可执行文件

r - 正确的编码方式——避免 for 循环

python - 如何在同一张图中绘制多个线性回归

python - 为什么输入模块会导出 "submodules"?

python - plotly 图隐藏和显示

java - 延迟改变颜色

android - 在android中实现循环执行?