在Eclipse / PyDev中使用msvcrt.getch()

7
我想在使用PyDev的Eclipse中读取单个字符时,使用msvcrt.getch()方法,但我发现它在此环境下无法正常工作(但在Windows控制台中可以)。你有什么解决办法吗?

这并不是真正可能的。请参见:https://stackoverflow.com/a/46303939/110451 - Fabio Zadrozny
1个回答

2
也许在PyDev中运行时可以使用sys.stdin.read?例如sys.stdin.read(1)从输入中读取1行...为了在Windows控制台和PyDev中使用相同的选择,可以基于操作系统和运行变量来运行。例如下面的代码读取有时间限制的用户输入。但是,如果程序的标准输入与另一个程序的标准输出管道连接在一起,则sys.stdin.isatty返回False并使用sys.stdin.read而不是msvcrt.getch来读取输入。
import sys, time
import platform
if platform.system() == "Windows":
    import msvcrt
else:
    from select import select

def input_with_timeout_sane(prompt, timeout, default):
    """Read an input from the user or timeout"""
    print prompt,
    sys.stdout.flush()
    rlist, _, _ = select([sys.stdin], [], [], timeout)
    if rlist:
        s = sys.stdin.readline().replace('\n','')
    else:
        s = default
        print s
    return s
def input_with_timeout_windows(prompt, timeout, default): 
    start_time = time.time()
    print prompt,
    sys.stdout.flush()
    input = ''
    read_f=msvcrt.getche
    input_check=msvcrt.kbhit
    if not sys.stdin.isatty( ):
        read_f=lambda:sys.stdin.read(1)
        input_check=lambda:True
    while True:
        if input_check():
            chr_or_str = read_f()
            try:
                if ord(chr_or_str) == 13: # enter_key
                    break
                elif ord(chr_or_str) >= 32: #space_char
                    input += chr_or_str
            except:
                input=chr_or_str
                break #read line,not char...        
        if len(input) == 0 and (time.time() - start_time) > timeout:
            break
    if len(input) > 0:
        return input
    else:
        return default

def input_with_timeout(prompt, timeout, default=''):
    if platform.system() == "Windows":
        return input_with_timeout_windows(prompt, timeout, default)
    else:
        return input_with_timeout_sane(prompt, timeout, default)

print "\nAnswer is:"+input_with_timeout("test?",10,"no input entered")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接