2

How can I get my Python program to end by pressing any key without pressing enter. So if the user types "c", the program should automatically end without pressing enter.

My code so far:

print("Hi everyone! This is just a quick sample code I made")
print("Press anykey to end the program.")
user2899653
  • 71
  • 2
  • 2
  • 7

1 Answers1

4

Usually, one would use input('>> ') (or raw_input('>> ') with Python3) in order to obtain a user command. However, this does require the user to submit the data after it is entered. So for your example, the user would type c then hit the Enter key.

If you're using Windows, then I think what you're after may be close to this answer. This example imports a library, msvcrt, which you can use to detect keyboard hits (using msvcrt.kbhit()). So the user would type c and your code could respond to that keystroke, without having to wait for the Enter key. Of course you will have to process the keys (i.e. check that the button was indeed a c) before executing the desired code (i.e. quit the application).


Edit: This answer assumes you have a while() loop doing stuff and/or waiting for user input. Such as the following:

import msvcrt

print("Hi everyone! This is just a quick sample code I made")
print("Press anykey to end the program.")

while(True):
    # Do stuff here.
    if msvcrt.kbhit():
        # The user entered a key. Check to see if it was a "c".
        if (msvcrt.getch() == "c"):
            break
        elif (msvcrt.getch() == <some other character>):
            # Do some other thing.

Of course to end the program for any keyboard hit, just get rid of the part that checks to see if the key is a "c".

Community
  • 1
  • 1
gary
  • 4,227
  • 3
  • 31
  • 58