在Eclipse / PyDev中使用msvcrt.getch() [英] Using msvcrt.getch() in Eclipse / PyDev

查看:295
本文介绍了在Eclipse / PyDev中使用msvcrt.getch()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Eclipse中使用PyDev中的 msvcrt.getch()来读取一个signe字符,但是我发现它只是不起作用(但它适用于Windows控制台)。

I wanted to use msvcrt.getch() in Eclipse with PyDev to read a signe char but I found out that it just don't work (but It works in the Windows console).

任何想法要做什么?

推荐答案

在PyDev中运行时,可能使用 sys.stdin.read sys.stdin.read(1)从输入读取1行...在Windows控制台和PyDev中使用基于os和运行变体进行相同的选择(使用 sys.stdin.isatty )。例如下一个代码读取timelimited用户输入。但是当在Windows控制台中运行程序的标准输入与其他程序的标准输出一起运行时,则 sys.stdin.isatty 返回 False 并用 sys.stdin.read 输入阅读,而不是 msvcrt.getch

Maybe use sys.stdin.read when run in PyDev? like sys.stdin.read(1) read 1 line from input...For use in Windows console and in PyDev make same selection based on os and run variants(using sys.stdin.isatty). For example next code read timelimited user input. But when run in Windows console if program's standard input is piped in with another program's standard output, then sys.stdin.isatty returns False and input read with sys.stdin.read, not 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")

这篇关于在Eclipse / PyDev中使用msvcrt.getch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆