简体   繁体   English

python退出无限循环与KeyboardInterrupt异常

[英]python exit infinite while loop with KeyboardInterrupt exception

My while loop does not exit when Ctrl+C is pressed. 按下Ctrl + C时,我的while循环不会退出。 It seemingly ignores my KeyboardInterrupt exception. 它似乎忽略了我的KeyboardInterrupt异常。 The loop portion looks like this: 循环部分如下所示:

while True:
  try:
    if subprocess_cnt <= max_subprocess:
      try:
        notifier.process_events()
        if notifier.check_events():
          notifier.read_events()
      except KeyboardInterrupt:
        notifier.stop()
        break
    else:
      pass
  except (KeyboardInterrupt, SystemExit):
    print '\nkeyboardinterrupt found!'
    print '\n...Program Stopped Manually!'
    raise

Again, I'm not sure what the problem is but my terminal never even prints the two print alerts I have in my exception. 同样,我不确定问题是什么,但我的终端甚至从未打印过我的异常中的两个打印警报。 Can someone help me figure this problem out? 有人能帮我解决这个问题吗?

Replace your break statement with a raise statement, like below: raise语句替换break语句,如下所示:

while True:
  try:
    if subprocess_cnt <= max_subprocess:
      try:
        notifier.process_events()
        if notifier.check_events():
          notifier.read_events()
      except KeyboardInterrupt:
        notifier.stop()
        print 'KeyboardInterrupt caught'
        raise  # the exception is re-raised to be caught by the outer try block
    else:
      pass
  except (KeyboardInterrupt, SystemExit):
    print '\nkeyboardinterrupt caught (again)'
    print '\n...Program Stopped Manually!'
    raise

The two print statements in the except blocks should execute with '(again)' appearing second. except块中的两个print语句应该以'(再次)'出现的第二个执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 KeyboardInterrupt 退出循环,然后在 python 中开始另一个循环 - Exit loop with KeyboardInterrupt then begin another loop in python 在while循环中生成绘图后退出KeyboardInterrupt - exit on KeyboardInterrupt after generating plots in while loop Python:乌龟-在无限循环中(退出)onclick吗? - Python: turtle - (exit)onclick while in infinite loop? 如何在不使用 KeyboardInterrupt 的情况下从按键退出 while 循环? [Python] - How do I exit a while loop from a keypress without using KeyboardInterrupt? [python] python 在无限循环期间如何处理键盘中断? - How does python handle KeyboardInterrupt during infinite loop? 如何通过键盘绑定或宏退出Python程序或循环? 键盘中断不起作用 - How to exit a Python program or loop via keybind or macro? Keyboardinterrupt not working Python如何手动结束收集数据的无限while循环,而不是结束代码而不使用KeyboardInterrupt? - Python how can I manually end an infinite while loop that's collecting data, without ending the code and not using KeyboardInterrupt? 循环时无法键盘中断 - Unable to KeyboardInterrupt while loop Python 键盘中断异常 - Python KeyboardInterrupt exception 有没有办法永远不会在Python的KeyboardInterrupt上退出? - Is there a way to never exit on KeyboardInterrupt in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM