【发布时间】:2021-01-15 22:52:03
【问题描述】:
这段代码运行良好,我唯一的问题是当我需要停止我的代码时,我输入 ctrl+c 尽管给出:
for thread in threads:
thread.alive = False
thread.join()
sys.exit(e)
在代码中,线程继续运行,说线程必须下载,即使在keyinterrupt之后它仍然继续下载。如何优雅地退出代码?
这是完整的代码:
try:
threads = []
while len(list1) != 0:
while len(threads) != 4:
time.sleep(1)
item = list1.pop(0)
thread = threading.Thread(target=func, args=(item, ))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
for thread in threads:
if not thread.is_alive():
# get results from thread
threads.remove(thread)
if len(list1) == 0:
logging.error("Nothing")
sys.exit(1)
except KeyboardInterrupt as e:
logging.error("Keyboard Interruption, code exiting!!")
list1.append(item)
logging.info(f'{item} Adding back to the list')
# whenever there is a keyboard interrupt kill all the threads
for thread in threads:
thread.alive = False
thread.join()
sys.exit(e)
except Exception as e:
logging.exception(f'Failed to initiate the threads : {e}')
sys.exit(1)
【问题讨论】:
标签: python python-3.x multithreading exception keyboardinterrupt