2017-01-11 4 views
0

파이썬에서 단일 키 누르기를 읽는 방법에 대해 많은 질문을 보았습니다. Windows의 경우 대답은 작동하는 msvcrt 모듈을 사용한다고 말합니다.Python 2.7 : Linux에서 단일 키 누르기를 읽는 방법 (특수 문자 포함)?

import termios, fcntl, sys, os 
def kbhit(): 
    fd = sys.stdin.fileno() 
    oldterm = termios.tcgetattr(fd) 
    newattr = termios.tcgetattr(fd) 
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO 
    termios.tcsetattr(fd, termios.TCSANOW, newattr) 
    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) 
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) 
    try: 
     while True: 
      try: 
       c = sys.stdin.read(1) 
       return True 
      except IOError: 
       return False 
    finally: 
     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) 
     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 

나이 :하지만 리눅스, 그들은이 같은 것을 사용

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 
getch = _Getch() 
그 두 가지의 문제들이 CNTRL-C와 같은 특수 문자를 읽을 수 없다는 것입니다

(^ C) 또는 화살표 키. 화살표 키와 같은 특수 문자를 포함하여 단일 키 누르기 을 읽는 Linux 방법이 있습니까?

답변

0

확인이 코드 조각 : 내 경우

def AllKeys(NormalInput=1): 
    """ Detect Key Input """ 

    import termios, sys, tty 

    fd = sys.stdin.fileno() 
    old_settings = termios.tcgetattr(fd) 

    tty.setraw(fd) 
    tty.setcbreak(fd) # Control + C 

    try: 
     #while True: 
     ch = sys.stdin.read(NormalInput) 

     if ch == '\x1b': 
     ch = ch.lstrip(' ') 
     ch += sys.stdin.read(2) 

    finally: 
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 
    return ch 

은 의도 작품으로! (가상

import socket 

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 

while True: 

    try: 

     InKey = AllKeys() 

     print InKey 

     if InKey == "\x03": 
      raise KeyboardInterrupt 

     elif InKey == '~': 
      break 

     else: 
      sock.sendto(InKey, (UDP_IP, UDP_PORT)) 

    except KeyboardInterrupt: 
     break 

sock.shutdown() 
sock.close() 

당신은 문자 Uinput와 가상 키보드 입력을받은 같이 처리 서버와 쉽게 확장 할 수 있습니다 : 그것은

그냥 UDP 클라이언트의이 간단한 예제를 확인 CTRL + '문자를'감지 HID 장치). 그런 다음 Iptables 규칙을 사용하여 포트 제어로 보안을 설정하십시오. 보안을 위해 ssh 터널링을 추가하십시오. 그렇지 않으면 ARP 캐시 중독 (MITM) 테스트에서 일반 데이터 트래픽이 표시됩니다.