我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用msvcrt.getch()。
def getch(): """ Interrupting program until pressed any key """ try: import msvcrt return msvcrt.getch() except ImportError: import sys import tty import termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
def _handle_keyboard_message(self): data = None if sys.platform in ['linux', 'darwin']: import select if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): data = sys.stdin.readline().rstrip() elif sys.platform == 'win32': import msvcrt if msvcrt.kbhit(): data = msvcrt.getch().decode('utf-8') if data == '\r': # Enter is pressed data = self.__q_kb self.__q_kb = '' else: print(data) self.__q_kb += data data = None else: pass return data ## Get the data message which was queued earlier.
def auto_run(self, files, dirs): while(True): print '\nTo show a list of files and dirs to be changed press "l"' print 'To update the destination press "u"' print 'To quit type q\n' command = msvcrt.getch() if command.lower() == 'l': self.run_type(files, dirs, commit_changes = False) elif command.lower() == 'u': self.update(files, dirs, commit_changes = True) break elif command.lower() == 'q': break else: pass
def wait_key(): ''' Wait for a key press on the console and return it. ''' result = None if os.name == 'nt': import msvcrt result = msvcrt.getch() else: import termios fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) try: result = sys.stdin.read(1) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) return result
def win_getpass(prompt='Password: ', stream=None): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) import msvcrt for c in prompt: msvcrt.putch(c) pw = "" while 1: c = msvcrt.getch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putch('\r') msvcrt.putch('\n') return pw
def getarrow(self): ''' Returns an arrow-key code after kbhit() has been called. Codes are 0 : up 1 : right 2 : down 3 : left Should not be called in the same program as getch(). ''' if os.name == 'nt': msvcrt.getch() # skip 0xE0 c = msvcrt.getch() vals = [72, 77, 80, 75] else: c = sys.stdin.read(3)[2] vals = [65, 67, 66, 68] return vals.index(ord(c.decode('utf-8')))
def _WaitForFinish(ob, timeout): end = time.time() + timeout while 1: if msvcrt.kbhit(): msvcrt.getch() break pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet(): stopEvent.clear() break try: if not ob.Visible: # Gone invisible - we need to pretend we timed # out, so the app is quit. return 0 except pythoncom.com_error: # Excel is busy (eg, editing the cell) - ignore pass if time.time() > end: return 0 return 1
def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less','more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
def getch(self): c = self.getbyt() if c is None: return None #print self.getbyt_avail() if self.posix: # for posix, keep possing input until have a full, valid escape code. while self.is_escape_code(c)<0: n = self.getbyt() if n is None: break c = c+n if self.is_escape_code(c)<1: self.ungetbyt(c[1:]) c = c[0] else: # for windows, get another byte if an extended symbol, then map. if c=='\xE0' or c=='\x00': n = self.getbyt() if n is not None: c = c+n # mapping from windows-dosbox inputs to posix-terminal inputs if c in self._winmap: c = self._winmap[c] return c
def getpass(self, prompt='Password : ', stream=None): """Prompt for password with echo off, using Unix getch().""" password = "" sys.stdout.write(prompt) while True: c = _win_getch() if os.name == 'nt' else self._unix_getch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': c = '' password += c sys.stdout.write("*") return password
def send_a_comend(self): data = "" while True: os.system("cls") print("") commend = raw_input("Enter a commend: ") self.client_socket.send(commend) print("please wait...") time.sleep(1) if commend == "screenshot": self.receive_screenshot(data) else: self.receive_commend(data) print("\npress any button to continue\n") key = getch()
def wait_at_exit(): """\ Wait at exit, but only if console window was opened separately. """ if not is_separate_console_window(): return import atexit import msvcrt def wait_at_end(): """Print a message and wait for a key""" sys.stderr.flush() sys.stdout.write('\n[Press any key]\n') sys.stdout.flush() msvcrt.getch() atexit.register(wait_at_end)
def wait_on_error(): """\ Wait on exception, but only if console window was opened separately. """ if not is_separate_console_window(): return import msvcrt import traceback def handle_exception(exctype, value, tb): # pylint: disable=invalid-name """Print an exception and wait for a key""" traceback.print_exception(exctype, value, tb) sys.stderr.flush() sys.stdout.write('\n[Press any key]\n') sys.stdout.flush() msvcrt.getch() sys.excepthook = handle_exception
def _find_getch(): try: import termios except ImportError: import msvcrt return msvcrt.getch import sys, tty def _getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch return _getch # read single character without waiting for '\n'
def getpass_getpass(prompt='Password:', stream=None): try: import msvcrt except ImportError: return _realgetpass(prompt, stream) password = '' sys.stdout.write(prompt) while True: ch = msvcrt.getch() if ch == '\b': if password: password = password[:-1] sys.stdout.write('\b \b') else: continue elif ch == '\r': sys.stdout.write(os.linesep) return password else: password += ch sys.stdout.write('*')
def pwd_input(): print 'password:', chars=[] while True: try: newChar=msvcrt.getch().decode('utf-8') except: print u'??????cmd????????????.' return raw_input('password:') if newChar in '\r\n': break elif newChar=='\b': if chars: del chars[-1] msvcrt.putch('\b'.encode('utf-8')) # ?????? msvcrt.putch(' '.encode('utf-8')) # ?????? msvcrt.putch('\b'.encode('utf-8')) # ???? else: chars.append(newChar) msvcrt.putch('*'.encode('utf-8')) # ???? return ''.join(chars)
def review_thumbnail(self): """ Display image and give user prompt to keep or discard """ fname = self.download('thumb')['thumb'] imgcat = os.getenv('IMGCAT', None) if imgcat is None: raise Exception("Set $IMGCAT to a terminal display program") cmd = '%s %s' % (imgcat, fname) print(cmd) os.system(cmd) print("Press Y to keep, N to delete, or any key to quit") while True: char = getch() if char.lower() == 'y': return True elif char.lower() == 'n': return False raise Exception('Cancel')
def read_character(): """Read one character from stdin. Returns -1 when no input is available.""" if sys.stdin.isatty(): # we're in console, read a character from the user char = getch() # check for ctrl-c (break) if ord(char) == 3: sys.stdout.write("^C") sys.stdout.flush() raise KeyboardInterrupt else: return char else: # input is redirected using pipes char = sys.stdin.read(1) # return -1 if there is no more input available return char if char != "" else -1
def adinput(prompt, default=None): putstr(prompt) if default is None: data = [] else: data = list(default) putstr(data) while True: c = getch() if c in '\r\n': break elif c == '\003': # Ctrl-C putstr('\r\n') raise KeyboardInterrupt elif c == '\b': # Backspace if data: putstr('\b \b') # Backspace and wipe the character cell data.pop() elif c in '\0\xe0': # Special keys getch() else: putch(c) data.append(c) putstr('\r\n') return ''.join(data)
def __call__(self): import msvcrt return msvcrt.getch()
def sanity_checks(self): # if run on platform that isn't windows if os.name != 'nt': print 'This program is currently only windows compatible. Sorry!' exit() # if drive not attached if not os.path.exists(self.ghost_drive): print self.ghost_drive + ' not attached' exit() # disallow c:\ drive if self.args['source'] == 'c': print "You probably don't want to be ghosting c:/ drive..." exit() # prevent recursive copying if self.normalise_backslash(self.args['source']) in self.normalise_backslash(self.args['dest']): print 'destination is part of the ghost - please see recursion in a dictionary' exit() # prompt if dest is root #if save_dir: if len(self.args['dest']) == 3: print "Are you sure that you want to copy to the root of the drive? y/n" answer = msvcrt.getch() if answer.lower() == 'y': pass else: exit() ############################### General Purpose #############################################
def get_char(): while msvcrt.kbhit(): msvcrt.getch() func = False char = msvcrt.getch() if char in ('\x00', '\xE0'): func = True while func: msvcrt.getch() func = False char = msvcrt.getch() if char in ('\x00', '\xE0'): func = True return char.replace('\r', '\n')
def alarm(seconds): time.sleep(seconds) while msvcrt.kbhit(): msvcrt.getch() while not msvcrt.kbhit(): winsound.Beep(440, 250) time.sleep(0.25)
def get_int(): while msvcrt.kbhit(): msvcrt.getch() buff = '' char = msvcrt.getch() while char != '\r' or not buff: if '0' <= char <= '9': sys.stdout.write(char) buff += char char = msvcrt.getch() sys.stdout.write('\n') return int(buff) ################################################################################
def _GetchWindows(): # This reads only one character. from msvcrt import getch return getch()
def getchar(echo): rv = msvcrt.getch() if echo: msvcrt.putchar(rv) _translate_ch_to_exc(rv) if PY2: enc = getattr(sys.stdin, 'encoding', None) if enc is not None: rv = rv.decode(enc, 'replace') else: rv = rv.decode('cp1252', 'replace') return rv
def getch(): # getchar(), getc(stdin) #PYCHOK flake fd = sys.stdin.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) return ch