i want to read in terminal keypressed while http server is running.
please hint me
[SOLVED] async read keypressed in terminal
[SOLVED] async read keypressed in terminal
Last edited by VladVons on Sun Feb 14, 2021 8:42 pm, edited 1 time in total.
Re: async read keypressed in terminal
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).
More info here: viewtopic.php?f=18&t=6954&p=39455
Re: async read keypressed in terminal [SOLVED]
thanks jimmo
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()
Re: async read keypressed in terminal
async non blocking keyboard input example
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()
- pythoncoder
- Posts: 5067
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: async read keypressed in terminal
Note that select.select is deprecated in favour of .poll or (usually more RAM efficient) .ipoll.
Peter Hinch
Re: async read keypressed in terminal
Peter, no theme in internet
Hope I`m on a right way with select.poll()
Hope I`m on a right way with select.poll()
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)