pythontextentergrok

Edit: Can I detect *any key* being pressed without input or installing any module?


I am writing a code where the text comes out like this:

import time
def animation(phrase):
  for i in phrase:
    print(i,end="",flush=True)     #Animates text to be printed out one by one
    time.sleep(0.035)
  print(phrase)

While the text is coming out one by one, the user can press enter in between the letters. After, that I have a code that asks for input and it assumes the enter key was the input the user put in.

I have tried using the keyboard module and other modules, I also want to avoid using the input function to detect whether it is an enter key or not.

I want to detect, at any point in my program when the enter key is pressed.

P.S I am using Grok, on online Python platform.


Solution

  • To detect keyboard input you will need to use the Curses library. Which is a built-in library in python.

    import curses
    import os
    
    
    def main(win):
        win.nodelay(True)
        key = ""
        win.clear()
        win.addstr("Detected key:") # curses version of print
    
        while True:
            try:
                key = win.getkey() # here it tries to detect the key
                win.clear()
                win.addstr("Detected key:")
                win.addstr(str(key)) #print the key to the display here
                if key == os.linesep:
                    break #check where there is a line seperation if so it breaks
            except Exception:
                # No input
                pass #If no key is pressed it just passes and loops again
    
    
    curses.wrapper(main)
    

    Here is an example where it checks whether a key is pressed and then displays it to the window.

    you can edit this to your needs.

    Tutorial on Curses Library

    Here is a minimal example in curses