1

I want to break an infinite loop when pressing space bar. I dont want to use Pygame, since it will produce a window.

How can i do it?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Jerin A Mathews
  • 8,572
  • 4
  • 26
  • 49

3 Answers3

2

I got an answer. We can use msvcrt.kbhit() to detect a keypress. Here is the code i wrote.

import msvcrt
while 1:
    print 'Testing..'
    if msvcrt.kbhit():
        if ord(msvcrt.getch()) == 32:
            break

32 is the number for space. 27 for esc. like this we can choose any keys.

Important Note: This will not work in IDLE. Use terminal.

Jerin A Mathews
  • 8,572
  • 4
  • 26
  • 49
1

Python has a keyboard module with many features. You Can Use It In Both Shell and Console. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard #Using module keyboard
while True:  #making a loop
    try:  #used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed(' '): #if key space is pressed.You can also use right,left,up,down and others like a,b,c,etc.
            print('You Pressed A Key!')
            break #finishing the loop
    except:
        pass

You can set it to multiple Key Detection:

if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
    #then do this

You Can Also Do Something like:

if keyboard.is_pressed('up') and keyboard.is_pressed('down'): #if both keys are pressed at the same time.
    #then do this

Hope This Helps You.
Thanks.

0

Using space will be difficult because each system maps it differently. If you are okay with enter, this code will do the trick:

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 = input()
    break
i += 1

Source

Community
  • 1
  • 1
abe
  • 504
  • 4
  • 13