I am trying to write a program that executes code whenever certain keys are pressed. I currently have this working, but unfortunately, this solution is very slow. Python doesn't find out about the key press until several seconds after the press.
command = "./STB_KEYCAP.sh"
popen = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
for stdout_line in iter(popen.stdout.readline, ""):
stdout_line = stdout_line.decode("utf-8")[0]
if stdout_line == "a":
channelUp()
elif stdout_line == "d":
channelDown()
STB_KEYCAP.py:
xinput test-xi2 --root 3| grep -A2 --line-buffered RawKeyRelease | while read -r line ;
do
#Trim line down and remove non digits
if [[ $line == *"detail"* ]];
then
key=$( echo $line | sed "s/[^0-9]*//g")
if [[ $key == "38" ]];
then
echo "a"
fi
if [[ $key == "40" ]];
then
echo "d"
fi
if [[ $key == "42" ]];
then
echo "g"
fi
sleep 0
fi
done
Again, this does work, but it takes several seconds in order to take action. Any tips on how to rewrite this to make it faster would be great!
I ended up finding a solution that worked well for me. The downside to this is that it requires the script to be run with administrator privileges, which is not an issue in my case, but might not work for some uses. I ended up parsing the /dev/input file for my keyboard, and determining keypresses from changes there. This solution ended up being very fast, and giving good results.
f = open( "/dev/input/event5", "rb" );
while 1:
data = f.read(24)
bytes = struct.unpack('4IHHI', data)
value = str(bytes).split(", ")
if value[6] == "0)":
if value[5] != "0":
# DO SOMETHING WITH KEY
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.