假设您具有PID,是否可以通过Shell脚本或终端命令来确定它是否具有主窗口(窗体),然后获取有关它的信息(标题)并显示/隐藏/关闭它?
由于您提到了命令行,因此以下脚本在终端窗口中运行。您可以使用pid
作为参数来运行它,例如:
python3 /path/to/script.py 1234
随后,将显示一个窗口(列表),您可以在其中选择一个(列表-)编号并键入要对其执行的选项:
Current Windows for pid 2189:
------------------------------------------------------------
[1] Niet-opgeslagen document 1 - gedit
[2] testbackup.py (~/Bureaublad) - gedit
------------------------------------------------------------
Type window number + option:
-k [kill (gracfully)]
-m [minimize]
-s [show]
Press <Enter> to cancel
------------------------------------------------------------
1 -k
如果没有窗户:
There are no windows for pid 1234
#!/usr/bin/env python3
import subprocess
import sys
pid = sys.argv[1]
message = """
------------------------------------------------------------
Type window number + option:
-k [kill (gracfully)]
-m [minimize]
-s s[how]
<Enter> to cancel
------------------------------------------------------------
"""
# just a helper function
get = lambda cmd: subprocess.check_output(cmd).decode("utf-8").strip()
# get the window list
wlist = [l.split()[0] for l in get(["wmctrl", "-lp"]).splitlines() if pid in l]
# create a indexed list of window name, id
wdata = [[i+1, get(["xdotool", "getwindowname", w_id]), w_id] \
for i, w_id in enumerate(wlist)]
# if the list is not empty (windows exist)
if wdata:
# print the window list
print("\nCurrent Windows for pid "+pid+":\n"+"-"*60)
for item in wdata:
print("["+str(item[0])+"]", item[1])
# ask for user input (see "message" at the top)
action = input(message)
action = action.split()
# run the chosen action
try:
subj = [item[2] for item in wdata if item[0] == int(action[0])][0]
options = ["-k", "-m", "-s"]; option = options.index(action[1])
command = [
["wmctrl", "-ic", subj],
["xdotool", "windowminimize", subj],
["wmctrl", "-ia", subj],
][option]
subprocess.Popen(command)
except (IndexError, ValueError):
pass
else:
print("There are no windows for pid", pid)
该脚本同时使用xdotool
和wmctrl
:
sudo apt-get install wmctrl xdotool
将脚本复制到一个空文件中,另存为 get_wlist.py
使用以下命令运行它:
python3 /path/to/get_wlist.py <pid>
要操纵,移动或关闭窗口,Linux上有两个重要工具:xdotool
和和wmctrl
。在这两个中,xdotool
可能是最强大的一个,我总体上更喜欢。尽管这两个工具的选项重叠,但是它们确实可以相互补充,因此我们只需要创建一个窗口列表即可wmctrl
。
因此,在大多数情况下,我最终会同时使用这两种工具。
该脚本的作用:
该脚本使用以下命令获取当前打开的窗口列表:
wmctrl -lp
它为我们提供了有关窗口ID和它所属的pid的信息,并带有如下输出:
0x05a03ecc 0 2189 jacob-System-Product-Name Niet-opgeslagen document 1 - gedit
然后,脚本过滤掉属于相应pid的窗口,并使用以下xdotool
命令查找窗口名称:
xdotool getwindowname <window_id>
并按名称显示找到的窗口。在引擎盖下,这些窗户被编号了。
随后,如果用户键入数字+选项,则会在所选窗口上执行相应的操作:
wmctrl -ic <window_id>
优雅地关闭窗口,或
xdotool windowminimize <window_id>
最小化所选窗口,或
wmctrl -ia <window_id>
举起窗户。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句