Using msvcrt.getch() in Eclipse / PyDev -
i wanted use msvcrt.getch()
in eclipse pydev read signe char found out don't work (but works in windows console).
any idea ?
maybe use sys.stdin.read
when run in pydev? sys.stdin.read(1)
read 1 line input...for use in windows console , in pydev make same selection based on os , run variants(using sys.stdin.isatty
). example next code read timelimited user input. when run in windows console if program's standard input piped in program's standard output, sys.stdin.isatty
returns false
, input read sys.stdin.read
, not msvcrt.getch
:
import sys, time import platform if platform.system() == "windows": import msvcrt else: select import select def input_with_timeout_sane(prompt, timeout, default): """read input 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 , (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")
Comments
Post a Comment