Search code examples
pythonsocketspycharmuser-input

How to get input from user with non- blocking function in Python?


I tried a lot to find how to use msvcrt.kbhit() but all I write, it works wrong... I tried:

while True:
    msg = ''
    print("Waiting for your message.\n")
    time.sleep(1)  # I tried with and without this line...  
    if msvcrt.kbhit():
        msg = msvcrt.getch().decode()
        print(msg, end='', flush=True)
        if ord(msg) == 13:  # Client enter 'ENTER'
            break

In this line: print(msg, end='', flush=True) end and flush are red ???

(Other than that, all the code works great! When I used INPUT - everything worked fine...)


Solution

  • Ok, this code is a 'replacement' for input(), but uses msvcrt.

    import msvcrt
    import time
    
    def nonblocking_input(prompt):
        print(prompt, end='', flush=True)
        msg = ''
        while True:
            if msvcrt.kbhit():
                ch = msvcrt.getch().decode()
                if ord(ch) == 13:
                    print()
                    return msg
                print(ch, end='', flush=True)
                msg += ch
            time.sleep(0.05)
    
    def main():
        msg = nonblocking_input('Waiting for your message: ')
        print(f'Ok, got:"{msg}"')
    
    main()
    

    I used time.sleep(0.05) to reduce the average cpu load.

    I tested this code with python at the windows cmd prompt because pycharm seems to have a problem with msvcrt