2013-04-18 9 views
7

में msvcrt.getch() का उपयोग करके मैं एक संकेत चिह्न पढ़ने के लिए पाइडेव के साथ ग्रहण में msvcrt.getch() का उपयोग करना चाहता था, लेकिन मुझे पता चला कि यह काम नहीं करता है (लेकिन यह विंडोज कंसोल में काम करता है)।eclipse/PyDev

कोई विचार क्या करना है?

+0

वास्तव में संभव नहीं है यही कारण है कि: लेकिन जब Windows कंसोल में चलाते हैं कार्यक्रम के मानक इनपुट में एक अन्य कार्यक्रम के मानक उत्पादन के साथ sys.stdin.isatty रिटर्न False और इनपुट sys.stdin.read, नहीं msvcrt.getch के साथ पठित पहुंचाया जाता है, तो। देखें: https://stackoverflow.com/a/46303939/110451 –

उत्तर

2

शायद पीडीडीव में चलाने पर sys.stdin.read का उपयोग करें? जैसे sys.stdin.read(1) इनपुट से 1 लाइन पढ़ें ... विंडोज कंसोल और पीईडीवी में उपयोग के लिए ओएस और रन वेरिएंट (sys.stdin.isatty का उपयोग करके) के आधार पर समान चयन करें। उदाहरण के लिए अगला कोड timelimited उपयोगकर्ता इनपुट पढ़ें।

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")