python - 在启动时运行 Python 脚本以记录 Linux 中的鼠标和键盘事件

标签 python linux cron keyboard

我相信很多人在问过这个问题或至少类似的问题之前。我的问题有点问题,但很简单。

我尝试在启动时使用 cron 和在 Linux 中编辑 etc/rc.local 文件来运行 Python 脚本,但这两种方法都无法运行我的 Python 脚本。

我的脚本使用键盘和鼠标的监听器对象记录键盘和鼠标的事件。我使用了一个名为 pynput 的第三方包,它依赖于 Xlib。我的脚本编辑的文件需要 sudo 访问权限,因此我必须使用 sudo 运行我的脚本。

你需要看一下脚本,所以你知道:

#!/usr/bin/env python
#backlight.py

from pynput.keyboard import Listener  as KeyboardListener
from pynput.mouse    import Listener  as MouseListener

import time

STATUS = ""                # Keyboard backlight ON/OFF status
turnOffSecs = 6           # Turn off keyboard backlight for x seconds of inactivity

# Keyboard brightness control file (change to your directory)
file_pth = "/sys/devices/platform/asus-nb-wmi/leds/asus::kbd_backlight/brightness"

def get_LEVEL():
    """return the current level of brightness of keyboard backlight"""
    with open(file_pth, "r") as f:
        brightness_level = f.read()[0]
    return brightness_level


class Sec_timer:
    """
    Sec_timer(until=None) 
        Create a timer that counts x number of seconds starting from 0

        until arg can be used for reseting the timer:

   *Example:

        timer = Sec_imer(20)
        while timer.elapsed < timer.until:                  
            timer.count()                # count a second
        else:
            timer.reset_timer()          # reset timer on exit
    """
    def __init__(self, until=None):
        self.until = until
        self.elapsed = 0 

    def count_sec(self): 
        "Count one second per-call"
        time.sleep(1)
        self.elapsed += 1

    def reset_timer(self):
        self.elapsed = 0 



timer = Sec_timer(turnOffSecs)           # Sec_timer(x) turn off keyboard backlight for x seconds of inactivity

# General event handler to reset timer
def reset_timer(*args):
    global STATUS

    timer.reset_timer()
    if STATUS == "OFF":
         # print(STATUS)
         with open(file_pth, "w") as f:
             f.write(current_brightnessLevel)
             f.close()
             STATUS="ON"



keyboard_listener = KeyboardListener(on_press=reset_timer, 
                             on_release=(lambda *args: None))

mouse_listener    = MouseListener(on_click=reset_timer, 
                             on_scroll=reset_timer, 
                             on_move=reset_timer)


keyboard_listener.start()
mouse_listener.start()


while True:
    timer.count_sec()
    if timer.elapsed > timer.until:
        # print "current brightness:" +  get_LEVEL()
        if  get_LEVEL() != "0":
            with open(file_pth, "w") as f: 
                current_brightnessLevel = get_LEVEL()
                f.write("0")
                STATUS = "OFF"

此脚本记录键盘和鼠标的事件,任何键盘或鼠标事件都会重置计时器。当 x 秒过去并且没有发生键盘或鼠标事件时,通过将“0”写入亮度文件夹来关闭键盘的背光灯。如果在脚本关闭背光后 发生任何鼠标或键盘事件,则根据背光的先前亮度级别打开键盘亮度。

使用终端运行脚本,效果非常好。但是,自动启动这个脚本是很棘手的;到目前为止,这是我尝试过的:

*请注意,我已将脚本文件设为可执行文件,并且 backlight.py 位于 /home/user 中:

1) 在终端中:

$ xhost +
$ sudo ./backlight.py

工作正常!

2) 使用 `etc/rc.local 我添加了:

xhost + 
cd /home/user/
./backlight.py

重启后脚本没有运行

3) 使用etc/rc.local

$ sudo crontab -e

@reboot xhost +
@reboot /home/user/backlight.py

重启后没有运行

由于 Xlib 的问题,我必须执行 xhost +。使用最后两种方法无效。我猜这是一个编程问题,也许它与 Xlib 有关?!

我知道这个脚本在与键盘 LED 接口(interface)方面很疯狂,如果你愿意的话,可以称之为“糟糕的脚本”。尽管我只是尝试使用文件输入/输出解决方案来解决驱动程序问题,因为我没有兴趣深入研究 Linux 驱动程序的详细信息,至少现在没有!

最佳答案

好吧,如果它需要 root 并且必须在启动时运行,为什么不创建自定义服务呢?

如果说您创建了一个自定义服务,systemd 可以为您启动它。 然后,您可以使用 sudo systemctl start yourservice 启动您的服务 您可以使用 sudo systemctl enable yourservice 确保它在启动时运行(作为 root)。无论用户如何,它都会启动。

我以前没有亲自做过,但应该不会太难。它基本上只是一个包含描述和执行命令的文件,在目录/etc/systemd/system 中创建。快速谷歌搜索给了我这个指南:https://blog.sdbarker.com/post/adding-custom-units-services-to-systemd-on-arch-linux/

希望对您有所帮助。

关于python - 在启动时运行 Python 脚本以记录 Linux 中的鼠标和键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43901427/

相关文章:

python - 使用 Python 抓取加拿大环境时出现 IOError

python - 如何使用seaborn为每个数据列设置绘图样式来绘制分类数据?

python - Django Formset 缺少管理表单数据

linux - 更改 Linux(CentOS 7) 中 Emacs 启动时的默认目录

php - 如何从 web 在 yii2 中运行控制台命令

ubuntu - 在crontab中执行php

python - Select(SQL语句中并未使用所有参数)

c++ - 无法在 OpenCV 中打开共享对象文件 'libopencv_shape.so.3.1'

linux - Linux内核中的内存保护