In Python, what is the simplest and most Pythonic way to pause a loop where a user keypress would restart the loop? I'm looking at doing this just as a debugging aid, so that I can output some debug messages to stdout from within the loop without dumping a ton of text at once.
Asked
Active
Viewed 396 times
1 Answers
6
If you are willing to limit the keypress to the Enter key, you can use input
(raw_input
in Python 2). Otherwise, you'll need something platform specific.
for i in range(10):
print(i)
input() # Loop continues after <Enter> is pressed
Alternatively, you could use pdb
, Python's built in debugger.

Community
- 1
- 1

Steven Rumbalski
- 44,786
- 9
- 89
- 119
-
1I use `raw_input` as a debugging aid all the time :). (perhaps I shouldn't say that too loudly ... the debugger police might find me). – mgilson Sep 05 '12 at 18:07
-
2Whoa, whoa, don't toss around accusations like that! – Andrew Gorcester Sep 05 '12 at 18:11
-
1I only resort to using a debugger when I'm faced with a Heisenbug (a bug that disappears when you look at it). Of course, I'm usually using fortran (which gdb unfortunately doesn't support all that well, or perhaps I'm just too lazy to make it work right) and MPI -- which makes it especially hard to figure out *which process* to attach the debugger to, etc... – mgilson Sep 05 '12 at 18:14
-
I suppose that while we're on the topic of debuggers, somebody should mention that [python has one](http://docs.python.org/library/pdb.html) – mgilson Sep 05 '12 at 18:16
-
Debuggers always have their place. As an embedded guy that can't always **see** what is going on in code without a debugger, it is pleasing to be able to just dump something to the screen sometimes. – ErikS Sep 05 '12 at 18:19
-
@mgilson, I'll check out pdb sometime. Right now this is quicker. Thanks! – ErikS Sep 05 '12 at 18:23