Linux下检测AppImage文件名变更并自动运行Python脚本的方法
检测AppImage文件名变更并触发Python脚本的方法
可以用Linux下的inotifywait工具实现文件系统事件监控,它能实时捕捉目录/文件的重命名、创建等操作,刚好满足你的需求。
步骤1:安装inotify-tools
inotifywait属于inotify-tools包,先通过对应系统的包管理器安装:
- Debian/Ubuntu系:
sudo apt install inotify-tools - RHEL/CentOS系:
sudo dnf install inotify-tools - Arch系:
sudo pacman -S inotify-tools
步骤2:编写监控脚本
创建一个bash脚本(比如monitor_appimage.sh),内容如下:
#!/bin/bash # 替换为你的AppImage所在目录 APPIMAGE_DIR="/path/to/your/appimage/directory" # 替换为你的Python脚本路径 PYTHON_SCRIPT="/path/to/your/update_desktop.py" # 可选:设置AppImage的基础名称前缀(比如原本叫xxx.AppImage,更新后是xxx-v1.2.3.AppImage) APPIMAGE_PREFIX="your_app_name" while true; do # 监控目录下的重命名/移动完成事件 inotifywait -e moved_to "$APPIMAGE_DIR" # 检查是否有匹配前缀的AppImage文件变更 if [ -n "$APPIMAGE_PREFIX" ]; then # 找到最新的匹配前缀的AppImage文件 latest_appimage=$(ls -t "$APPIMAGE_DIR"/"$APPIMAGE_PREFIX"*.AppImage | head -n1) if [ -f "$latest_appimage" ]; then # 运行Python脚本,可将最新文件名作为参数传递 python3 "$PYTHON_SCRIPT" "$latest_appimage" fi else # 无前缀匹配时直接触发脚本 python3 "$PYTHON_SCRIPT" fi done
步骤3:设置脚本可执行并运行
给脚本添加执行权限:chmod +x monitor_appimage.sh
后台运行脚本:./monitor_appimage.sh &
如果需要开机自动启动,推荐创建systemd服务:
- 创建服务文件:
sudo nano /etc/systemd/system/appimage-monitor.service - 写入内容:
[Unit] Description=Monitor AppImage filename changes and update desktop shortcut [Service] ExecStart=/path/to/your/monitor_appimage.sh User=your_username Restart=always [Install] WantedBy=multi-user.target
- 启用并启动服务:
sudo systemctl daemon-reloadsudo systemctl enable --now appimage-monitor.service
注意事项
- 如果AppImage更新是先删除旧文件再创建新文件,可将
inotifywait的事件改为-e create,或者同时监控多个事件:-e moved_to,create APPIMAGE_PREFIX用于过滤无关文件的变更,避免误触发脚本- Python脚本中可通过
sys.argv[1]获取传递的最新AppImage文件名(如果需要的话)
内容的提问来源于stack exchange,提问作者space
相关产品推荐
相关产品推荐

