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

  • AceHoodVEVO

    AceHoodVEVO

    12 Mayıs 2009
  • Gali B

    Gali B

    1 EYLÜL 2006
  • RobertDuskin

    RobertDuskin

    12 HAZİRAN 2008