Here is a Python implementation of my earlier C code post. The C code is run from Python via a system call. It's not pretty, but it works.
This is key.c
This is getkey.py
Code:
1. Download the two programs below: C code key.c Python code getkey.py2. Compile the C code gcc key.c -o key3. Run the Python code (may or may not need sudo) sudo python3 getkey.py
Code:
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include "termios.h"int main(int argc,char *argv[]) { int n,cmd,len; unsigned char c; struct termios tattr; FILE *stream; unsigned char *cp; if(argc == 2) cmd = argv[1][0]; else return(0); cp = (unsigned char*)&tattr; len = sizeof(tattr); if(cmd == '0') // switch to single key mode { // Save the terminal attributes so we can restore them later tcgetattr(STDIN_FILENO, &tattr); stream = fopen("/tmp/term.dat","wb"); if(stream == NULL) return(0); for(n = 0 ; n < len ; ++n) fputc(cp[n],stream); fclose(stream); /* Set the terminal modes. */ tattr.c_lflag &= ~(ICANON|ECHO|ISIG|ECHONL|IEXTEN); tattr.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); tattr.c_oflag = OPOST|ONLCR; tattr.c_cflag &= ~(CSIZE | PARENB); tattr.c_cflag |= CS8; tattr.c_cc[VMIN] = 0; tattr.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO,TCSAFLUSH,&tattr); } else if(cmd == '1') // read key { n = read(STDIN_FILENO,&c,1); if(n == 0) return(0); return(c); } else if(cmd == '2') // restore original mode { stream = fopen("/tmp/term.dat","rb"); if(stream == NULL) return(0); for(n = 0 ; n < len ; ++n) cp[n] = fgetc(stream); fclose(stream); tcsetattr(STDIN_FILENO,TCSANOW,&tattr); return(0); } return(0); }
This is getkey.py
Code:
import osdef getkey(): os.system('key 0') # switch mode key = 0 while(key == 0): n = os.system('key 1') # read key key = n >> 8 os.system('key 2') # restore mode if(key == 3): exit(0) # CTL-C press return(key) print("Press any key - prints ASCII code (press x to exit)")key = 0while(key != 120): key = getkey() print(key)
Statistics: Posted by petzval — Thu Jul 25, 2024 1:38 pm