0

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!

Alex Collette
  • 1,664
  • 13
  • 26
  • Perhaps using signals; if that too limited, how about using https://pypi.org/project/keyboard/ – gregory Jun 27 '19 at 15:58
  • on Linux I use [AutoKey](https://github.com/autokey/autokey) which has GUI to assing Python script to key comibnation. It is created with Python so you can see its source code or use it as normal program – furas Jun 27 '19 at 16:02

1 Answers1

0

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
Alex Collette
  • 1,664
  • 13
  • 26