我在 Rhythmbox 上测试了下面的脚本,没有出现任何错误。
如果目标进程的窗口不在前面(一秒内),则在后台运行下面的脚本将暂停目标进程,如果应用程序附带它,则将声音静音。
每当窗口再次出现在前面时,该过程就会恢复到原来的位置,并且声音再次起作用。
如果目标进程/应用程序根本没有运行,脚本将切换到更长的周期(模式),每五秒只检查一次目标应用程序是否运行。这样,如果脚本没有工作要完成,它的汁液就会非常少。
#!/usr/bin/env python3
import subprocess
import time
# ---set the proc to pause when not the active window
wclass = "rhythmbox"
# ---
def get(cmd):
# just a helper function to not repeat verbose subprocess sections
try:
return subprocess.check_output(cmd).decode("utf-8").strip()
except subprocess.CalledProcessError:
pass
while True:
# the longer period: application is not running (saving fuel)
time.sleep(5)
front1 = ""
while True:
# if the application runs, switch to a shorter response time
time.sleep(1)
# get the possible pid, get() returns "None" if not running,
# script then switches back to 5 sec check
pid = get(["pgrep", wclass])
if pid:
front2 = wclass in get([
"xprop", "-id", get(["xdotool", "getactivewindow"])
])
# run either kill -stop or kill -cont only if there is
# a change in the situation
if front2 != front1:
if front2 == True:
cm = ["kill", "-cont", pid]
print("run") # just a test indicator, remove afterwards
else:
cm = ["kill", "-stop", pid]
print("stop") # just a test indicator, remove afterwards
subprocess.Popen(cm)
front1 = front2
else:
break
Run Code Online (Sandbox Code Playgroud)
该脚本需要xdotool获取最前面窗口的信息:
sudo apt-get install xdotool
Run Code Online (Sandbox Code Playgroud)pause_app.py在脚本的 head 部分,将进程名称设置为 pause (replace rhythmbox)。
通常这与(的第一部分)相同WM_CLASS,但在您的情况下,我怀疑这是否不应该steam或其他。运行以确保
ps -u <yourname>
Run Code Online (Sandbox Code Playgroud)
做出有根据的猜测,然后
kill <pid>
(the process id)
Run Code Online (Sandbox Code Playgroud)
去检查。
通过以下命令运行脚本:
python3 /path/to/pause_app.py
Run Code Online (Sandbox Code Playgroud)
并检查是否一切正常。
如果一切正常,请添加到启动应用程序:Dash > 启动应用程序 > 添加。然后添加命令:
python3 /path/to/pause_app.py
Run Code Online (Sandbox Code Playgroud)该脚本可以轻松编辑以针对多个应用程序,但首先请查看这是否是您需要的。
如果您希望在目标窗口不在前面时通常将声音静音,请将暂停应用程序的命令替换为静音 (/unmute) sound的命令。然后脚本变成:
sudo apt-get install xdotool
Run Code Online (Sandbox Code Playgroud)
用法与第一个脚本完全相似。