Py学习  »  Python

iPython:用try/except杀死for循环?

Mastiff • 4 年前 • 385 次点击  

我知道我应该避免陷入这些情况,但我喜欢使用iPython并在实验期间保留变量。我将Spyder中的部分代码粘贴到中,让它们运行,然后检查变量等。现在,我有一部分代码如下:

for a in range(bignum):
  try:
    <something>
  except:
    print('Badness')

我一开始就意识到我犯了一个错误,但是现在我不能用ctrl-C来阻止它,因为try/except只是打印消息并继续前进。有没有一种方法可以在不中断会话的情况下停止循环?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54952
 
385 次点击  
文章 [ 1 ]  |  最新文章 4 年前
SyntaxVoid supports Monica
Reply   •   1 楼
SyntaxVoid supports Monica    4 年前

你可以用 break 在里面 except 从句让自己脱离循环。或者,可以移动for循环 try/except块。如果你想做一件事 KeyboardInterrupt (ctrl+c)还有另一件事 ,两种都可以单独抓到。

for a in range(big_num):
  try:
    pass # Do your thing
  except KeyboardInterrupt:
    print("You pressed ctrl c...")
    break
  except Exception as e: # Any other exception
    print(str(e)) # Displays the exception without raising it
    break

try:
  for a in range(big_num):
    pass # Do your thing
except KeyboardInterrupt:
  print("You pressed ctrl c...")
except Exception as e:
  print(str(e))