[SOLVED] async read keypressed in terminal
Posted: Fri Feb 14, 2020 6:57 pm
i want to read in terminal keypressed while http server is running.
please hint me
please hint me
Please see the new forum at
https://forum.micropython.org/
You can use select or poll on sys.stdin to see if there are characters available (which you can then read using sys.stdin.read).
Code: Select all
import uasyncio as asyncio
import sys
import select
async def Task1():
while True:
print('Task1')
await asyncio.sleep(1)
async def Task2():
while True:
await asyncio.sleep(0.1)
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
ch = sys.stdin.read(1)
print('none block input char', ch)
loop = asyncio.get_event_loop()
loop.create_task(Task1())
loop.create_task(Task2())
loop.run_forever()
Code: Select all
import sys
import uasyncio as asyncio
import select
def GetInputChr():
R = ''
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
R = sys.stdin.read(1)
return R
async def GetInputStr(aPrompt = ''):
R = ''
while True:
K = GetInputChr()
if (K):
if (ord(K) == 10): # enter
print()
return R
elif (ord(K) == 27): # esc
return ''
elif (ord(K) == 127): # bs
R = R[:-1]
else:
R += K
sys.stdout.write("%s%s \r" % (aPrompt, R))
await asyncio.sleep(0.1)
async def Test1():
while True:
print('Test1')
await asyncio.sleep(5)
async def Test2():
S = ''
while True:
print('Test2')
S = await GetInputStr('Prompt: ')
print('input', S)
loop = asyncio.get_event_loop()
loop.create_task(Test1())
loop.create_task(Test2())
loop.run_forever()
Code: Select all
class TKbdTerm():
def __init__(self):
self.Poller = select.poll()
self.Poller.register(sys.stdin, select.POLLIN)
def GetChr(self):
for s, ev in self.Poller.poll(500):
return s.read(1)
async def Input(self, aPrompt = ''):
R = ''
while True:
K = self.GetChr()
if (K):
if (ord(K) == 10): # enter
print()
return R
elif (ord(K) == 27): # esc
return ''
elif (ord(K) == 127): # bs
R = R[:-1]
else:
R += K
sys.stdout.write("%s%s \r" % (aPrompt, R))
await asyncio.sleep(0.2)