Exit the loop by pressing enter without blocking. How can I improve this method?

So, I read a little about how to exit the while loop by pressing the enter key, and I came up with the following:

import sys, select, os switch = 1 i = 1 while switch == 1: os.system('cls' if os.name == 'nt' else 'clear') print "I'm doing stuff. Press Enter to stop me!" print i while sys.stdin in select.select([sys.stdin], [], [], 0)[0]: line = raw_input() if not line: print "Finished! =]" switch = 0 else: print "Finished! =]" switch = 0 i = i+1 

Is there any way to remove this? In particular, "if not line" and the next "else" look randomly. Is it possible to combine them into one? Best alternative to using a "switch"?

Initially, if I typed a bunch of characters, and then hit enter, it won’t stop the loop. I would need to press a key again. The if and else components are designed to configure it so that it exits the first time you press input.

+4
python input loops exit enter
source share
1 answer

This worked for me:

 import sys, select, os i = 0 while True: os.system('cls' if os.name == 'nt' else 'clear') print "I'm doing stuff. Press Enter to stop me!" print i if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: line = raw_input() break i += 1 

You only need to check if the input will be stdin once (since the first input will end the loop). If the condition line / does not have a result for you, you can combine them into a single if statement. Then, using only one while statement, you can now use break instead of setting a flag.

+9
source share

All Articles