移除驱动器后自动关闭 Nautilus 窗口

Jak*_*ake 6 command-line nautilus scripts mount 16.04

我记得在使用 12.04(也可能是 14.04)时,如果我删除了当前安装并在 Nautilus 窗口中打开的驱动器,该窗口将自动关闭。

现在在 16.04 中,/media/{username}如果我删除一个打开的驱动器,打开的窗口会自动恢复到媒体目录 ( )。有没有办法恢复这个功能?

Jac*_*ijm 7

补丁功能

在 nautilus 的首选项中,据我所知,没有修复它的选项;- 在首选项中找不到任何内容。然而,我们可以使用一个很小的、极低的背景脚本来修补它。额外的处理器负担是虚无的。

剧本

#!/usr/bin/env python3
import subprocess
import os
import time

def get(cmd):
    try:
        return subprocess.check_output(cmd).decode("utf-8").strip()
    except subprocess.CalledProcessError:
        pass

curruser = os.environ["USER"]
nautpid = get(["pgrep", "nautilus"])
connected1 = [l for l in get("lsblk").splitlines() if "media" in l]
wlist1 = [l.strip() for l in get(["wmctrl", "-lp"]).splitlines() if nautpid in l]

t = 0
while True:
    time.sleep(1.5)
    connected2 = [l for l in get("lsblk").splitlines() if "media" in l]
    time.sleep(0.5)
    while True:
        wlist = get(["wmctrl", "-lp"])
        if wlist:
            break
    wlist2 = [l.strip() for l in wlist.splitlines() if nautpid in l]
    removed = [l for l in connected1 if not l in connected2]
    if removed:
        close = [
            w for w in wlist2 if all([
                not w in wlist1,
                any([
                    w.endswith(" "+curruser),
                    w.endswith(" Home")]),
                ])
            ]
        for w in close:
            subprocess.Popen(["wmctrl", "-ic", w.split()[0]])
    connected1 = connected2
    wlist1 = wlist2
    # periodically (re)set nautpid to fix if nautilus crashed somehow
    t += 1
    if t == 20:
        nautpid = get(["pgrep", "nautilus"])
        t = 0
Run Code Online (Sandbox Code Playgroud)

如何使用

  1. 需要wmctrl安装脚本

    sudo apt-get install wmctrl
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将脚本复制到一个空文件中,另存为 close_removed.py

  3. 测试-通过命令运行它

    python3 /path/to/close_removed.py
    
    Run Code Online (Sandbox Code Playgroud)

    连接一个或多个驱动器,在它们自动安装后将其移除。他们的窗口应该关闭。

  4. 如果一切正常,请将其添加到启动应用程序:Dash > 启动应用程序 > 添加。添加命令:

    /bin/bash -c "sleep 15 && python3 /path/to/close_removed.py"
    
    Run Code Online (Sandbox Code Playgroud)

解释

  • 外部驱动器安装在 /media/<username>/<drivename>
  • 如果驱动器断开连接,相应的nautilus窗口将恢复为(至少在我的系统上)/media/<username>。因此,该窗口以当前用户的名字(重新)命名。
  • 不幸的是,我们不能简单地关闭所有nautilus以当前用户命名的窗口,可能会发生不匹配的情况。然而,可以安全地假设在驱动器断开连接后立即重命名为当前用户的窗口是代表已删除驱动器的窗口。

这就是脚本的工作方式,使用:

pgrep nautilus 
Run Code Online (Sandbox Code Playgroud)

...在脚本启动时,获取 nautilus 的 pid

wmctrl -lp
Run Code Online (Sandbox Code Playgroud)

...获取鹦鹉螺的窗户

lsblk
Run Code Online (Sandbox Code Playgroud)

...留意可能断开连接的驱动器

wmctrl -ic <window_id>
Run Code Online (Sandbox Code Playgroud)

...关闭目标窗口

笔记

该脚本的周期为两秒,这意味着驱动器需要连接至少两秒才能工作。