Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Continuously monitoring user input in an asynchronous manner within Python

$
0
0

I'm seeking a Python script that persistently awaits user input for some time at each interval. Should the user fail to provide input within this timeframe, the script should automatically execute a predefined operation and continue this process indefinitely.

To achieve this, I've crafted a code snippet wherein the getch function captures a character input from the user. The program awaits the user's input within a timeout period. If the user fails to provide input within this interval, a notification is issued to indicate that the time has elapsed.

import threadingdef getch(input_str: list) -> None:"""Gets a single character"""    try:        import msvcrt        input_str.append(msvcrt.getch().decode("utf-8"))    except ImportError:        import sys        import termios        import tty        fd = sys.stdin.fileno()        oldsettings = termios.tcgetattr(fd)        try:            tty.setraw(fd)            ch = sys.stdin.read(1)        finally:            termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)        input_str.append(ch)def input_with_timeout(timeout):    print("You have {} seconds to enter something:".format(timeout))    input_str = []    input_thread = threading.Thread(target=getch, args=(input_str,))    input_thread.start()    input_thread.join(timeout)    if input_thread.is_alive():        print("Time's up! Performing default operation.")    else:        print("You entered:", input_str)while True:    input_with_timeout(5)

When the user provides input within the allotted time, the system functions correctly. However, should time elapse, two issues arise: firstly, there is a glitch in text display, resulting in misplacement of the text, and secondly, the user must input their response multiple times, as a single attempt does not seem to register the input accurately.

enter image description hereBecause libraries such as pynput and keyboard have limitations in some environments, I cannot use them.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>