Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I break out of this itertools infinite loop?

In the REPL, we can usually interrupt an infinite loop with a sigint, i.e. ctrl+c, and regain control in the interpreter.

>>> while True: pass
... 
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>

But in this loop, the interrupt seems to be blocked and I have to kill the parent process to escape.

>>> *x, = itertools.repeat('x')
^C^C^C^C^C^C^C^C^\^\^\^\^\^Z^Z^Z^Z

Why is that?

like image 248
wim Avatar asked Mar 30 '16 21:03

wim


People also ask

Does Break stop all loops Python?

The Python break statement immediately terminates a loop entirely.

Can a for loop on its own end up in an infinite loop?

A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }

How do you range infinity in Python?

As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.

What type of loop would you use to create an infinite loop in Python?

A few types of Infinite Loop in Python include the While statement, the If statement, the Continue statement, and the Break statement.


1 Answers

The KeyboardInterrupt is checked after each Python instruction. itertools.repeat and the tuple generation is handled in C Code. The interrupt is handled afterwards, i.e. never.

like image 84
Daniel Avatar answered Oct 25 '22 16:10

Daniel