Python非阻塞控制台输入

时间:2010-03-09 11:17:05

标签: python windows input

我正在尝试用Python创建一个简单的IRC客户端(作为一种项目,当我学习语言时)。

我有一个循环用于接收和解析IRC服务器发送给我的内容,但是如果我使用raw_input来输入内容,它会在循环中停止循环,直到输入内容(显然)。

如何在没有循环停止的情况下输入内容?

提前致谢。

(我认为我不需要发布代码,我只想输入一些没有而1 循环停止的东西。)

编辑:我在Windows上。

10 个答案:

答案 0 :(得分:42)

对于Windows,仅限控制台,请使用msvcrt模块:

import msvcrt

num = 0
done = False
while not done:
    print(num)
    num += 1

    if msvcrt.kbhit():
        print "you pressed",msvcrt.getch(),"so now i will quit"
        done = True

对于Linux,此article描述了以下解决方案,它需要termios模块:

import sys
import select
import tty
import termios

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print(i)
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == '\x1b':         # x1b is ESC
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

对于跨平台,或者如果你想要一个GUI,你可以使用Pygame:

import pygame
from pygame.locals import *

def display(str):
    text = font.render(str, True, (255, 255, 255), (159, 182, 205))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery

    screen.blit(text, textRect)
    pygame.display.update()

pygame.init()
screen = pygame.display.set_mode( (640,480) )
pygame.display.set_caption('Python numbers')
screen.fill((159, 182, 205))

font = pygame.font.Font(None, 17)

num = 0
done = False
while not done:
    display( str(num) )
    num += 1

    pygame.event.pump()
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        done = True

答案 1 :(得分:23)

这是我见过的最棒的solution 1 。粘贴在这里以防链接断开:

#!/usr/bin/env python
'''
A Python class implementing KBHIT, the standard keyboard-interrupt poller.
Works transparently on Windows and Posix (Linux, Mac OS X).  Doesn't work
with IDLE.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as 
published by the Free Software Foundation, either version 3 of the 
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

'''

import os

# Windows
if os.name == 'nt':
    import msvcrt

# Posix (Linux, OS X)
else:
    import sys
    import termios
    import atexit
    from select import select


class KBHit:

    def __init__(self):
        '''Creates a KBHit object that you can call to do various keyboard things.
        '''

        if os.name == 'nt':
            pass

        else:

            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

            # Support normal-terminal reset at exit
            atexit.register(self.set_normal_term)


    def set_normal_term(self):
        ''' Resets to normal terminal.  On Windows this is a no-op.
        '''

        if os.name == 'nt':
            pass

        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)


    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)


    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 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    
if __name__ == "__main__":

    kb = KBHit()

    print('Hit any key, or ESC to exit')

    while True:

        if kb.kbhit():
            c = kb.getch()
            if ord(c) == 27: # ESC
                break
            print(c)

    kb.set_normal_term()

<子> 1 Simon D. Levy制作,compilation of software的一部分,是Gnu Lesser General Public License编写并发布的。{/ sub>

答案 2 :(得分:10)

这是一个使用单独的线程在linux和windows下运行的解决方案:

import sys
import threading
import time
import Queue

def add_input(input_queue):
    while True:
        input_queue.put(sys.stdin.read(1))

def foobar():
    input_queue = Queue.Queue()

    input_thread = threading.Thread(target=add_input, args=(input_queue,))
    input_thread.daemon = True
    input_thread.start()

    last_update = time.time()
    while True:

        if time.time()-last_update>0.5:
            sys.stdout.write(".")
            last_update = time.time()

        if not input_queue.empty():
            print "\ninput:", input_queue.get()

foobar()

答案 3 :(得分:8)

在Linux上,这里是mizipzor代码的重构,这使得它更容易,如果你必须在多个地方使用这个代码。

import sys
import select
import tty
import termios

class NonBlockingConsole(object):

    def __enter__(self):
        self.old_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())
        return self

    def __exit__(self, type, value, traceback):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)


    def get_data(self):
        if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
            return sys.stdin.read(1)
        return False

以下是如何使用此代码:此代码将打印一个持续增长的计数器,直到您按ESC键。

with NonBlockingConsole() as nbc:
    i = 0
    while 1:
        print i
        i += 1
        if nbc.get_data() == '\x1b':  # x1b is ESC
            break

答案 4 :(得分:4)

我认为curses库可以提供帮助。

import curses
import datetime

stdscr = curses.initscr()
curses.noecho()
stdscr.nodelay(1) # set getch() non-blocking

stdscr.addstr(0,0,"Press \"p\" to show count, \"q\" to exit...")
line = 1
try:
    while 1:
        c = stdscr.getch()
        if c == ord('p'):
            stdscr.addstr(line,0,"Some text here")
            line += 1
        elif c == ord('q'): break

        """
        Do more things
        """

finally:
    curses.endwin()

答案 5 :(得分:4)

我最喜欢的获取非阻塞输入的方法是在线程中使用python input():

import threading

class KeyboardThread(threading.Thread):

    def __init__(self, input_cbk = None, name='keyboard-input-thread'):
        self.input_cbk = input_cbk
        super(KeyboardThread, self).__init__(name=name)
        self.start()

    def run(self):
        while True:
            self.input_cbk(input()) #waits to get input + Return

showcounter = 0 #something to demonstrate the change

def my_callback(inp):
    #evaluate the keyboard input
    print('You Entered:', inp, ' Counter is at:', showcounter)

#start the Keyboard thread
kthread = KeyboardThread(my_callback)

while True:
    #the normal program executes without blocking. here just counting up
    showcounter += 1

独立于操作系统,只有内部库,支持多字符输入

答案 6 :(得分:1)

使用python3.3及更高版本,您可以使用本答案中提到的asyncio模块。 您必须重新考虑代码才能使用asyncioPrompt for user input using python asyncio.create_server instance

答案 7 :(得分:0)

我会按照米奇·陈(Mickey Chan)的话做,但我会使用unicurses而不是普通的诅咒。 Unicurses是通用的(可在所有或至少几乎所有操作系统上运行)

答案 8 :(得分:0)

以下是上述解决方案之一的类包装:

#!/usr/bin/env python3

导入线程

导入队列

NonBlockingInput类:

def __init__(self, exit_condition):
    self.exit_condition = exit_condition
    self.input_queue = queue.Queue()
    self.input_thread = threading.Thread(target=self.read_kbd_input, args=(), daemon=True)
    self.input_thread.start()

def read_kbd_input(self):
    done_queueing_input = False
    while not done_queueing_input:
        console_input = input()
        self.input_queue.put(console_input)
        if console_input.strip() == self.exit_condition:
            done_queueing_input = True

def input_queued(self):
    return_value = False
    if self.input_queue.qsize() > 0:
        return_value = True
    return return_value

def input_get(self):
    return_value = ""
    if self.input_queue.qsize() > 0:
        return_value = self.input_queue.get()
    return return_value

如果名称 =='主要':

NON_BLOCK_INPUT = NonBlockingInput(exit_condition='quit')

DONE_PROCESSING = False
INPUT_STR = ""
while not DONE_PROCESSING:
    if NON_BLOCK_INPUT.input_queued():
        INPUT_STR = NON_BLOCK_INPUT.input_get()
        if INPUT_STR.strip() == "quit":
            DONE_PROCESSING = True
        else:
            print("{}".format(INPUT_STR))

答案 9 :(得分:0)

由于我发现answers above中的一个有用,因此下面是类似方法的示例。这段代码在输入时会产生节拍器效果。

区别在于此代码使用闭包而不是类,这对我来说更加直接。此示例还包含一个标志,用于通过my_thread.stop = True杀死线程,但不使用全局变量。我通过(ab)利用python函数是对象的事实来做到这一点,因此甚至可以从内部对其进行猴子修补。

注意:停止线程时应格外小心。如果您的线程中的数据需要某种清理过程,或者该线程产生了自己的线程,则此方法会毫不客气地杀死这些进程。

# Begin metronome sound while accepting input.
# After pressing enter, turn off the metronome sound.
# Press enter again to restart the process.

import threading
import time
import winsound  # Only on Windows

beat_length = 1  # Metronome speed


def beat_thread():
    beat_thread.stop = False  # Monkey-patched flag
    frequency, duration = 2500, 10
    def run():  # Closure
        while not beat_thread.stop:  # Run until flag is True
            winsound.Beep(frequency, duration)
            time.sleep(beat_length - duration/1000)
    threading.Thread(target=run).start()


while True:
    beat_thread()
    input("Input with metronome. Enter to finish.\n")
    beat_thread.stop = True  # Flip monkey-patched flag
    input("Metronome paused. Enter to continue.\n\n")