1

Basically, I am playing around with the msvcrt library in Python, and my code is giving me weird results. When I have a 'getch' string that is the enter key ('\r') returned from a function, my main while loop automatically picks the returned ('\r') variable as a keyboard entry from the user. It triggers the unwanted condition of breaking the while loop as if the user had hit the enter key. Can someone please explain what I'm not seeing?

import msvcrt

def test():
    while True:
        if msvcrt.kbhit():
            a = msvcrt.getch().decode('ASCII')
            break
    return a

uiStr = ''
newStr = ''
while True:
    if msvcrt.kbhit():
        toFunc = msvcrt.getch().decode('ASCII')
        if (toFunc=='\r'): #this condition gets activated if return var from last loop is '\r'
            break
        elif toFunc.isalpha()==True:
            newStr = test()  #If '\r' is passed from function, it activates the kbhit condition in the next loop iteration
            uiStr += newStr
        else:
            uiStr += toFunc
        print(uiStr)
Shaido
  • 27,497
  • 23
  • 70
  • 73
Daniel Zhou
  • 11
  • 1
  • 3

0 Answers0