按Ctrl + C后,如何使Python在程序停止之前完成作业? [英] After pressing Ctrl+C how do I make Python finish the jobs before the program stops?
问题描述
我有4个工作的无限循环,如下所示:
I have a infinite loop of 4 jobs like this:
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个工作然后停止.
After I press Ctrl + C, I can't make sure it does all 4 jobs and then stops.
这似乎在睡觉时起作用,但是有睡眠延迟.
This seems to work when it is sleeping, but it has the sleep delay.
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
是否有可能在任何时候按下某个键时,它将完成该循环中的所有作业,更新数据库,然后停止.
Is it possible that in any time when I press some key, it does all jobs in this loop, update database and then stops.
推荐答案
好的,所以我为您提供两个答案.
Ok so i have two answers for you.
第一个答案
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
并且所有作业都已完成,该零件将退出.
This piece will exit once a KeyboardInterrupt
has been triggered and all jobs have finished.
第二个答案
我只是用谷歌搜索了禁用键盘中断python 并发现了如何覆盖键盘中断? (Python),并想出了一些稍有不同的代码.
I simply googled disable keyboard interrupt python and found this How can I override the keyboard interrupt? (Python) and came up with this code which is slightly different.
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)
我从没使用过信号库(甚至没有听说过),所以这里是文档
I have never used the signal library (or even heard of it) so here is the documentation
编辑,我从未使用过全局变量,因此我的用法可能是错误的.
EDIT I have never used global variables so my usage may be wrong.
编辑两次第一个示例由于没有在每个步骤中捕获错误,因此只能在80%〜的时间内工作
EDIT TWO The first example works only 80%~ of the time due to not trapping the error at each step
这篇关于按Ctrl + C后,如何使Python在程序停止之前完成作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!