英文:
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...)
英文:
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...)
答案1
得分: 0
以下是代码部分的翻译:
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('等待您的消息:')
print(f'好的,收到消息:“{msg}”')
main()
我使用了 time.sleep(0.05)
来降低平均 CPU 负载。
我在 Windows 的命令提示符中使用 python
测试了这段代码,因为似乎 pycharm
对 msvcrt
有问题。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论