简体   繁体   English

使用python获取系统范围的按键

[英]Getting system wide key presses with python

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. 直到按下按键几秒钟后,Python才发现有关按键的信息。

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: 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. 我最终为键盘解析了/ dev / input文件,并从那里的更改确定按键。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM