"Diary" インターネットさんへの恩返し

いつもソースコードコピペばかりなので,みなさまへ少しばかりの恩返しを

pythonでEnterなしで一文字入力を受け付ける方法



スポンサーリンク

キーボードにraspberrypiのGPIOの入出力を割り当てて、LEDを光らせたり、モーターの回転数を上げたり、mp3でドレミファソならしたりしたかったのでいろいろググったら見つかった。


How to enter a input without pressing enter [duplicate]


raw_input()やin_put()でも可能なんだけど、Enterキーを入力しないと値を変数に入れれないのもあって、キー入力後すぐに変数に値を挿入する方法を探していた。


どうも、やり方としてはWindows環境ではmsvcrtモジュールを使えばできるようなんだけど、Raspberry piでやりたかったのでLinuxで動くものが必要だった。


そこで見つけたのがgetch()っていう誰かが作ってくれたクラス。

これを使えばいとも簡単に キー入力+即座にエンター となる。



サンプルをここに書きます。

sample.py

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()

while True:
    getch = _Getch()
    x = getch()

    if (int(x) == 1):
        print "\n"
        print 'correct'
        print x
    else:
        print "\n"
        print 'wrong'
        print x

実行結果

$  sudo python sample.py

#ここで「1」を入力 
correct
1

#ここで「2」を入力 
wrong
2

#ここで「3」を入力 
wrong
3

#ここで「4」を入力 
wrong
4

こちらで応用しました。azwoo.hatenablog.com