Python msvcrt 模块,kbhit() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用msvcrt.kbhit()

项目:OpenCLGA    作者:PyOCL    | 项目源码 | 文件源码
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.
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __ichr(self):
        addr = self.__stck.pop()
        # Input Routine
        while msvcrt.kbhit():
            msvcrt.getwch()
        while True:
            char = msvcrt.getwch()
            if char in '\x00\xE0':
                msvcrt.getwch()
            elif char in string.printable:
                char = char.replace('\r', '\n')
                msvcrt.putwch(char)
                break
        item = ord(char)
        # Storing Number
        self.__heap.set_(addr, item)
项目:miros    作者:aleph2c    | 项目源码 | 文件源码
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')))
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
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
项目:overhead_mobile_tracker    作者:NU-MSR    | 项目源码 | 文件源码
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')))
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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
项目:RobotControl    作者:vdwel    | 项目源码 | 文件源码
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')))
项目:speech_ml    作者:coopie    | 项目源码 | 文件源码
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')))
项目:skaff    作者:jhxie    | 项目源码 | 文件源码
def timed_key_get(seconds: int) -> str:
    """
    Gets a single key press from the terminal within the given number of
    'seconds' and returns a 'str' representing the key pressed; returns empty
    "" string upon time out.

    Based on the version from StackOverflow by Paul:
    http://stackoverflow.com/questions/3471461/raw-input-and-timeout/3911560
    """
    if "posix" == os.name:
        return timeout(seconds)(key_get)()
    elif "nt" == os.name:
        start_time = time.time()
        key = str()

        while True:
            if msvcrt.kbhit():
                key = key_get()
                break
            if len(key) == 0 and (time.time() - start_time) > seconds:
                raise TimeoutError()
        return key
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def input_with_timeout_windows(prompt, timeout, default): 
    start_time = time.time()
    print prompt,
    sys.stdout.flush()
    input = ''
    while True:
        if msvcrt.kbhit():
            chr = msvcrt.getche()
            if ord(chr) == 13: # enter_key
                break
            elif ord(chr) >= 32: #space_char
                input += chr
        if len(input) == 0 and (time.time() - start_time) > timeout:
            break
    if len(input) > 0:
        return input
    else:
        return default
项目:otRebuilder    作者:Pal3love    | 项目源码 | 文件源码
def waitForKeyPress():
    """Force the DOS Prompt window to stay open so the user gets
    a chance to see what's wrong."""
    import msvcrt
    print('(Hit any key to exit)', file=sys.stderr)
    while not msvcrt.kbhit():
        pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __iint(self):
        addr = self.__stck.pop()
        # Input Routine
        while msvcrt.kbhit():
            msvcrt.getwch()
        buff = ''
        char = msvcrt.getwch()
        while char != '\r' or not buff or len(buff) == 1 and buff in '+-':
            if char in '\x00\xE0':
                msvcrt.getwch()
            elif char in '+-' and not buff:
                msvcrt.putwch(char)
                buff += char
            elif '0' <= char <= '9':
                msvcrt.putwch(char)
                buff += char
            elif char == '\b':
                if buff:
                    buff = buff[:-1]
                    msvcrt.putwch(char)
                    msvcrt.putwch(' ')
                    msvcrt.putwch(char)
            char = msvcrt.getwch()
        msvcrt.putwch(char)
        msvcrt.putwch('\n')
        item = int(buff)
        # Storing Number
        self.__heap.set_(addr, item)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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')
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)

################################################################################
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def alarm(seconds):
    time.sleep(seconds)
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)

################################################################################
项目:Wall-EEG    作者:neurotechuoft    | 项目源码 | 文件源码
def kbhit():
    ''' Returns True if keyboard character was hit, False otherwise.
    '''
    if sys.platform.startswith('win32'):
        return msvcrt.kbhit()   
    else:
        dr,dw,de = select([sys.stdin], [], [], 0)
        return dr != []

# -------------------------------------------------------------------------
项目:miros    作者:aleph2c    | 项目源码 | 文件源码
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)
项目:miros    作者:aleph2c    | 项目源码 | 文件源码
def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()

        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []


# Test
项目:rfcat-firsttry    作者:atlas0fd00m    | 项目源码 | 文件源码
def keystop(delay=0):
    if os.name == 'posix':
        return len(select.select([sys.stdin],[],[],delay)[0])
    else:
        return msvcrt.kbhit()
项目:FileBot    作者:Searinox    | 项目源码 | 文件源码
def clear_key():
    while msvcrt.kbhit()!=0:
        msvcrt.getch()
    return
项目:FileBot    作者:Searinox    | 项目源码 | 文件源码
def get_key():
    retval=[0,0]
    if msvcrt.kbhit()!=0:
        retval[0]=ord(msvcrt.getch())
        if msvcrt.kbhit()!=0:
            retval[1]=ord(msvcrt.getch())
    if retval[0]==224:
        if retval[1]!=0:
            retval[0]=0
    return retval
项目:multi-cloud-control    作者:robertpeteuil    | 项目源码 | 文件源码
def input_flush():
    """Flush the input buffer on posix and windows."""
    try:
        import sys, termios  # noqa
        termios.tcflush(sys.stdin, termios.TCIFLUSH)
    except ImportError:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def stdin_ready():
        return msvcrt.kbhit()


# On linux only, window.flip() has a bug that causes an AttributeError on
# window close.  For details, see:
# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def stdin_ready():
        return msvcrt.kbhit()

#-----------------------------------------------------------------------------
# Callback functions
#-----------------------------------------------------------------------------
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _stdin_ready_nt():
    """Return True if there's something to read on stdin (nt version)."""
    return msvcrt.kbhit()
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _run_stdio(self):
        """Runs the process using the system standard I/O.

        IMPORTANT: stdin needs to be asynchronous, so the Python
                   sys.stdin object is not used. Instead,
                   msvcrt.kbhit/getwch are used asynchronously.
        """
        # Disable Line and Echo mode
        #lpMode = DWORD()
        #handle = msvcrt.get_osfhandle(sys.stdin.fileno())
        #if GetConsoleMode(handle, ctypes.byref(lpMode)):
        #    set_console_mode = True
        #    if not SetConsoleMode(handle, lpMode.value &
        #            ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
        #        raise ctypes.WinError()

        if self.mergeout:
            return self.run(stdout_func = self._stdout_raw,
                    stdin_func = self._stdin_raw_block)
        else:
            return self.run(stdout_func = self._stdout_raw,
                    stdin_func = self._stdin_raw_block,
                    stderr_func = self._stderr_raw)

        # Restore the previous console mode
        #if set_console_mode:
        #    if not SetConsoleMode(handle, lpMode.value):
        #        raise ctypes.WinError()
项目:OpenCLGA    作者:PyOCL    | 项目源码 | 文件源码
def get_input():
    data = None
    try:
        time.sleep(0.01)
        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':
            global lines_input
            import msvcrt
            if msvcrt.kbhit():
                data = msvcrt.getch().decode('utf-8')
                if data == '\r':
                    # Enter is pressed
                    data = lines_input
                    lines_input = ''
                else:
                    print(data)
                    lines_input += data
                    data = None
        else:
            pass
    except KeyboardInterrupt:
        data = 'exit'
    return data
项目:OpenCLGA    作者:PyOCL    | 项目源码 | 文件源码
def get_input():
    global lines
    data = None
    try:
        if sys.platform in ['linux', 'darwin']:
            import select
            time.sleep(0.01)
            if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
                data = sys.stdin.readline().rstrip()
        elif sys.platform == 'win32':
            import msvcrt
            time.sleep(0.01)
            if msvcrt.kbhit():
                data = msvcrt.getch().decode('utf-8')
                if data == '\r':
                    # Enter is pressed
                    data = lines
                    lines = ''
                else:
                    lines += data
                    print(data)
                    data = None
        else:
            pass
    except KeyboardInterrupt:
        data = 'exit'
    return data
项目:FrozenBottle    作者:freieslabor    | 项目源码 | 文件源码
def getbyt(self):
        res = None
        if len(self.buf)>0:
            res = self.buf[0]
            self.buf = self.buf[1:]
        elif self.posix:
            nw = sys.stdin.read(32)
            if len(nw)>0:
                self.buf = nw[1:]
                res = nw[0]
        else:
            if msvcrt.kbhit():
                res = msvcrt.getch()
        return res
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def stdin_ready():
        return msvcrt.kbhit()

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:Console-Car-Racer    作者:gaborvecsei    | 项目源码 | 文件源码
def userKeyboardInput():
    """
    Reads the input from the user
    :return: Keycode or None if there was no hit
    """

    x = msvcrt.kbhit()
    if x:
        ret = msvcrt.getch()
    else:
        ret = None
    return ret
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
def check_key():
    if msvcrt is None:
        return False
    else:
        if msvcrt.kbhit()!=0:
            q=msvcrt.getch()

            return q in "q" 
        else:
            return False
项目:isf    作者:w3h    | 项目源码 | 文件源码
def check_key():
    if msvcrt is None:
        return False
    else:
        if msvcrt.kbhit():
            q = ensure_unicode(msvcrt.getch())
            return q
    return ""
项目:isf    作者:w3h    | 项目源码 | 文件源码
def check_key():
    if msvcrt is None:
        return False
    else:
        if msvcrt.kbhit():
            q = ensure_unicode(msvcrt.getch())
            return q
    return ""
项目:overhead_mobile_tracker    作者:NU-MSR    | 项目源码 | 文件源码
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)
项目:overhead_mobile_tracker    作者:NU-MSR    | 项目源码 | 文件源码
def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()

        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []
项目:overhead_mobile_tracker    作者:NU-MSR    | 项目源码 | 文件源码
def flush(self):
        """
        flush stdin... untested on Windows"
        """
        if os.name == 'nt':
            while self.kbhit():
                self.getch()
        else:
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
        return


# Test
项目:rfcat    作者:atlas0fd00m    | 项目源码 | 文件源码
def keystop(delay=0):
    if os.name == 'posix':
        return len(select.select([sys.stdin],[],[],delay)[0])
    else:
        return msvcrt.kbhit()
项目:RobotControl    作者:vdwel    | 项目源码 | 文件源码
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)
项目:RobotControl    作者:vdwel    | 项目源码 | 文件源码
def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()

        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []


# Test
项目:speech_ml    作者:coopie    | 项目源码 | 文件源码
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)
项目:speech_ml    作者:coopie    | 项目源码 | 文件源码
def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()
        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []


# Test
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def stdin_ready():
        return msvcrt.kbhit()


# On linux only, window.flip() has a bug that causes an AttributeError on
# window close.  For details, see:
# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def stdin_ready():
        return msvcrt.kbhit()

#-----------------------------------------------------------------------------
# Callback functions
#-----------------------------------------------------------------------------
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _stdin_ready_nt():
    """Return True if there's something to read on stdin (nt version)."""
    return msvcrt.kbhit()
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _run_stdio(self):
        """Runs the process using the system standard I/O.

        IMPORTANT: stdin needs to be asynchronous, so the Python
                   sys.stdin object is not used. Instead,
                   msvcrt.kbhit/getwch are used asynchronously.
        """
        # Disable Line and Echo mode
        #lpMode = DWORD()
        #handle = msvcrt.get_osfhandle(sys.stdin.fileno())
        #if GetConsoleMode(handle, ctypes.byref(lpMode)):
        #    set_console_mode = True
        #    if not SetConsoleMode(handle, lpMode.value &
        #            ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
        #        raise ctypes.WinError()

        if self.mergeout:
            return self.run(stdout_func = self._stdout_raw,
                    stdin_func = self._stdin_raw_block)
        else:
            return self.run(stdout_func = self._stdout_raw,
                    stdin_func = self._stdin_raw_block,
                    stderr_func = self._stderr_raw)

        # Restore the previous console mode
        #if set_console_mode:
        #    if not SetConsoleMode(handle, lpMode.value):
        #        raise ctypes.WinError()
项目:OWASP-ZSC-API    作者:viraintel    | 项目源码 | 文件源码
def check_key():
    if msvcrt is None:
        return False
    else:
        if msvcrt.kbhit():
            q = ensure_unicode(msvcrt.getch())
            return q
    return ""