Python msvcrt.getch() Examples

The following are 30 code examples of msvcrt.getch(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module msvcrt , or try the search function .
Example #1
Source File: keyboard_hit.py    From RocketCEA with GNU General Public License v3.0 7 votes vote down vote up
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'))) 
Example #2
Source File: getpass.py    From meddle with MIT License 7 votes vote down vote up
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 
Example #3
Source File: control.py    From pi-tracking-telescope with MIT License 6 votes vote down vote up
def _find_getch():
    try:
        import termios
    except ImportError:
        # Non-POSIX. Return msvcrt's (Windows') getch.
        import msvcrt
        return msvcrt.getch

    # POSIX system. Create and return a getch that manipulates the tty.
    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 
Example #4
Source File: getpass.py    From oss-ftp with MIT License 6 votes vote down vote up
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 
Example #5
Source File: page.py    From Computable with MIT License 6 votes vote down vote up
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() 
Example #6
Source File: yubikey.py    From Commander with MIT License 6 votes vote down vote up
def get_input_interrupted(prompt):
    # TODO: refactor to use interruptable prompt from prompt_toolkit in api.py:193 (login: process 2fa error codes).
    #  This method to be removed.
    if os.name == 'nt':
        global win_cancel_getch

        print(prompt)
        win_cancel_getch = False
        result = b''
        while not win_cancel_getch:
            if msvcrt.kbhit():
                ch = msvcrt.getch()
                if ch in [b'\r', b'\n']:
                    break
                result += ch
            else:
                time.sleep(0.1)
        if win_cancel_getch:
            raise KeyboardInterrupt()
        return result.decode()
    else:
        return input(prompt) 
Example #7
Source File: getpass.py    From BinderFilter with MIT License 6 votes vote down vote up
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 
Example #8
Source File: getpass.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: testMSOfficeEvents.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: getpass.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: utils.py    From fandogh-cli with MIT License 6 votes vote down vote up
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'))) 
Example #12
Source File: buzzer.py    From qb with MIT License 6 votes vote down vote up
def interpret_keypress(other_allowable=""):
    """
    See whether a number was pressed (give terminal bell if so) and return
    value.  Otherwise returns none.  Tries to handle arrows as a single
    press.
    """
    press = getch()
    if press == '\x1b':
        getch()
        getch()
        press = "direction"

    if press.upper() in other_allowable:
        return press.upper()

    if press != "direction" and press != " ":
        try:
            press = int(press)
        except ValueError:
            press = None
    return press 
Example #13
Source File: wizardofoz.py    From saywizard with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #14
Source File: _termui_impl.py    From hitch with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #15
Source File: common.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def __call__(self):
        import msvcrt
        return msvcrt.getch() 
Example #16
Source File: keyboard_macos.py    From mouse with GNU General Public License v3.0 5 votes vote down vote up
def run(self,session,cmd_data):
        h.info_info("Press Ctrl-C to stop.")
        h.info_info("Device keyboard:")
        while 1:
            key = getch()
            if key == chr(3):
                return ""
            payload = """tell application "System Events"
            keystroke \""""+key+"""\"
            end tell"""
            session.send_command({"cmd":"applescript","args":payload})
        return "" 
Example #17
Source File: keyboard_macos.py    From mouse with GNU General Public License v3.0 5 votes vote down vote up
def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old) 
Example #18
Source File: randpool.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getch(self):
                termios.tcflush(0, termios.TCIFLUSH) # XXX Leave this in?
                return os.read(self._fd, 1) 
Example #19
Source File: randpool.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getch(self):
                c = msvcrt.getch()
                if c in ('\000', '\xe0'):
                    # function key
                    c += msvcrt.getch()
                return c 
Example #20
Source File: _tutorial.py    From explorer-hat with MIT License 5 votes vote down vote up
def getch():
        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 
Example #21
Source File: randpool.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def randomize(self, N = 0):
        "Adds N bits of entropy to random pool.  If N is 0, fill up pool."
        import os, string, time
        if N <= 0:
            bits = self.bits - self.entropy
        else:
            bits = N*8
        if bits == 0:
            return
        print(bits,'bits of entropy are now required.  Please type on the keyboard')
        print('until enough randomness has been accumulated.')
        kb = KeyboardEntry()
        s=''    # We'll save the characters typed and add them to the pool.
        hash = self._hash
        e = 0
        try:
            while e < bits:
                temp=str(bits-e).rjust(6)
                os.write(1, temp)
                s=s+kb.getch()
                e += self.add_event(s)
                os.write(1, 6*chr(8))
            self.add_event(s+hash.new(s).digest() )
        finally:
            kb.close()
        print('\n\007 Enough.  Please wait a moment.\n')
        self.stir_n()   # wash the random pool.
        kb.close(4) 
Example #22
Source File: HmcRestClient.py    From HmcRestClient with Apache License 2.0 5 votes vote down vote up
def back_to_menu():
    print("\nPress ENTER to Proceed ")
    msvcrt.getch()
    os.system("cls") 
Example #23
Source File: _termui_impl.py    From planespotter with MIT License 5 votes vote down vote up
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 
Example #24
Source File: getch.py    From rshell with MIT License 5 votes vote down vote up
def __call__(self):
        import msvcrt
        ch = msvcrt.getch()
        if ch == b'\xe0':
            ch = msvcrt.getch()
            if ch in self.keymap:
                ch = self.keymap[ch]
        return ch 
Example #25
Source File: _termui_impl.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
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 
Example #26
Source File: utils.py    From fandogh-cli with MIT License 5 votes vote down vote up
def getch(self):
        ''' Returns a keyboard character after kbhit() has been called.
            Should not be called in the same program as getarrow().
        '''

        s = ''

        if os.name == 'nt':
            return msvcrt.getch()
                # .decode('utf-8')

        else:
            return sys.stdin.read(1) 
Example #27
Source File: recipe-578366.py    From code with MIT License 5 votes vote down vote up
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)

################################################################################ 
Example #28
Source File: recipe-578366.py    From code with MIT License 5 votes vote down vote up
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') 
Example #29
Source File: recipe-579095.py    From code with MIT License 5 votes vote down vote up
def __call__(self):
        import msvcrt
        import time

        # Delay timeout to match UNIX behaviour
        time.sleep(1)

        # Check if there is a character waiting, otherwise this would block
        if msvcrt.kbhit():
            return msvcrt.getch()

        else:
            return 
Example #30
Source File: recipe-578367.py    From code with MIT License 5 votes vote down vote up
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)

################################################################################