LoginSignup
21
13

More than 5 years have passed since last update.

pythonでキー入力を検出する(tty)

Posted at

前回termiosを使って同じことをしたんだけど、ttyでもやってみた。
[前回]http://qiita.com/tortuepin/items/9ede6ca603ddc74f91ba

import sys
import termios
import tty

#標準入力のファイルディスクプリタを取得
fd = sys.stdin.fileno()

#fdの端末属性をゲットする
old = termios.tcgetattr(fd)

try:
    #標準入力のモードを切り替える
    #cbreakとrawのどっちもエンターいらなくなるけど、rawはctrl-cとかもきかなくなる??
    tty.setcbreak(sys.stdin.fileno())
    #tty.setraw(sys.stdin.fileno())
    ch = sys.stdin.read(1)

finally:
    # fdの属性を元に戻す
    termios.tcsetattr(fd, termios.TCSANOW, old)

print(ch)

こっちのほうが前回よりも自由度は低いけど簡単です。

cbreakとrawの違い

21
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
13