I'm debugging some code in PyCharm by stepping through line-by-line. The code involves a long for-loop, but for debugging purposes, I don't need to iterate through the whole thing. Instead, I'd like to break out after a few iterations. I'm trying to figure out how to do so without modifying my code to have special debugging instructions.
Example for loop
indices = range(10000, 0, -1)
for i, val in enumerate(indices):
print(val) # I can tell that it's working after a few iterations
The first thing I tried was typing break
in the debugging console when paused at the print(val)
line. This resulted in a syntax error
SyntaxError: 'break' outside loop
I also thought about using the debugging console line to modify the variable that I am enumerating over. For example, entering
indices = []
This has no effect on the iterator. Apparently, the iterator has an independent copy of the variable.
In another language, Java for example, I would take advantage of the termination condition, but python loops don't have a termination condition. I could rewrite my for-loop as a while-loop so that it would have an explicit termination condition, but that would obfuscate the code.
The other option would be to add special debugging instructions. For example,
mode = 'debug'
indices = range(10000, 0, -1)
for i, val in enumerate(indices):
print(val) # I can tell that it's working after a few iterations
if mode == 'debug' and i % 10:
break
I dislike doing this because inevitably, one of these special instructions gets left in after debugging is finished and mucks everything up.
Do I have any other options to break out of the loop from the debug console or without modifying the code?
question from:
https://stackoverflow.com/questions/65929403/break-out-of-loop-from-console-while-in-debug-mode 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…