Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python - Break out of loop from console while in debug mode

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I dislike doing this because inevitably, one of these special instructions gets left in after debugging is finished and mucks everything up.

Python for loops just aren't designed to be changed during execution, besides hard coding break, return or throwing StopIteration. (You are debugging, so either change the range in the loops expression list, or let it run through). The reason being the advantages of straightforward simplicity outweigh exposing the for loop counter - see PEP 212.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...