如何在Python中使用非阻塞函数从用户获取输入?

huangapple go评论99阅读模式
英文:

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 测试了这段代码,因为似乎 pycharmmsvcrt 有问题。

英文:

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

huangapple
  • 本文由 发表于 2023年7月23日 22:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定