Teddy C
Teddy C

Reputation: 1016

How to break from infinite generator loops from interactive shell in python

I was learning itertools in Python and accidentally invoked an infinite loop in iPython shell, here's what my inputs:

import itertools as it
list(it.zip_longest(it.count(), [1,2]))

The last line would run indefinitely until the computer crashes.

I tried to terminate the execution with Ctrl-C, but it didn't work.

How do I force the execution to terminate in this case?

Upvotes: 1

Views: 498

Answers (1)

CK__
CK__

Reputation: 1311

Python is a interpreted language hence it checks for instruction after each line. The same happens with Ctrl-C too.

Ctrl-C sends KeyboardInterrupt to Python interpreter and it is checked after each Python instruction but the output generation by it.zip_longest(it.count(), [1,2]) is handled in C Code and the interrupt is handled afterwards but interpreter never checks for next instruction hence even on Ctrl-C the execution doesn't stop.

Upvotes: 2

Related Questions