SORU
4 ŞUBAT 2009, ÇARŞAMBA


Python kullanıcıdan tek bir karakter okumak

Kullanıcı giriş tek bir karakter okumak için bir yolu var mı? Örneğin, terminalde bir tuşa basın ve döndü (tür getch() gibi). Bunun için Windows içinde bir işlevi olduğunu biliyorum, ama cross-platform bir şey istiyorum.

CEVAP
4 ŞUBAT 2009, ÇARŞAMBA


Burada Windows ve Linux hem de tek bir karakter okumak diyor bir site için bir link: http://code.activestate.com/recipes/134892/

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, 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


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • alex maybury

    alex maybury

    20 Aralık 2007
  • fireflame65

    fireflame65

    27 Mart 2007
  • YouChewBu

    YouChewBu

    26 Ocak 2009