I have an app, which has to make a get request to my API every 4 seconds to stay authorized. My issue is, it uses a whole lot of input()
which is blocking the thread to make the request. I tried to write a whole module to combat this, but it is still blocking. I have spent so long trying to get a non-blocking input. I have tried almost everything on SO. Here is the class I wrote for non-blocking input. (it has a function nbput()
that functions almost entirely like python's input()
)
from pynput import keyboard
from pynput.keyboard import Key
import threading
import sys
from functools import partial
uinput = ''
lastKey = ''
modifierKey = ''
class NonBlockingInput:
arg0 = ''
def __init__(self):
global listener
listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
print('1')
def on_press(self, key):
global lastKey
global modifierKey
try:
sys.stdout.write(key.char)
lastKey = key.char
except AttributeError:
if key == Key.space:
lastKey = ' '
sys.stdout.write(' ')
return
modifierKey = key
def on_release(self, key):
pass
def nbinput(self, prompt):
global uinput
global listener
global lastKey
global modifierKey
global arg0
listener.start()
sys.stdout.write(prompt)
while True:
if modifierKey == Key.enter:
sys.stdout.write('\n')
value_returned = partial(self.retrieved_data_func, arg0)
break
elif modifierKey == Key.backspace:
spaceString = ''
for _ in range(0, len(uinput)):
spaceString += ' '
uinput = uinput[:-1]
sys.stdout.write('\r')
sys.stdout.write(spaceString)
sys.stdout.write('\r')
sys.stdout.write(uinput)
modifierKey = ''
else:
uinput += lastKey
lastKey = ''
def retrieved_data_func(self):
arg0 = 0
return arg0
def nbput(prompt=''):
global collectionThread
nonBlockingInput = NonBlockingInput()
collectionThread = threading.Thread(nonBlockingInput.nbinput(prompt))
collectionThread.start()
return NonBlockingInput.retrieved_data_func()
if __name__ == '__main__':
print(nbput())```