舊答案:

舊答案:

我正在使用多點觸控,並嘗試使用相同的手勢在不同的應用程式上執行不同的操作。

我有一個 python 腳本,基本上有效。

Bot 我如何在應用程式之間做出選擇?如何取得活動視窗標題?

謝謝

編輯系統資訊:

  • Python 2.7.6
  • Ubuntu 14.04(統一)

答案1

以下更新版本。我將保留舊答案,而不是刪除獲得投票的答案。

#!/usr/bin/env python3

import gi
gi.require_version("Wnck", "3.0")
from gi.repository import Wnck

scr = Wnck.Screen.get_default()
scr.force_update()
print(scr.get_active_window().get_name())

或取得 xid:

print(scr.get_active_window().get_xid())

或(並不奇怪)獲取 pid:

print(scr.get_active_window().get_pid())

另請參閱此處獲取Wnck.Window 方法


舊答案:

xprop我只是解析 or和xwit的輸出wmctrl(您可能必須wmctrl先安裝sudo apt-get install wmctrl:)。 xprop 給出很多有關 Windows 的資訊。

xprop -root

為您提供有關活動視窗的資訊、視窗 ID 以及

wmctrl -l

為您提供目前開啟的視窗的清單。使用該-p選項還可以為您提供有關視窗所屬的 pid 的資訊。結合起來,您可以獲得所需的所有資訊。

例如:

在 python 3 中,使用子進程 check_output():

取得活動視窗(id):

-使用 xprop

# [1]
import subprocess

command = "xprop -root _NET_ACTIVE_WINDOW | sed 's/.* //'"
frontmost = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8").strip()

print(frontmost)
> 0x38060fd

-使用 xprop,在 python“內部”解析它

# [2]
import subprocess

command = "xprop -root _NET_ACTIVE_WINDOW"
frontmost = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8").strip().split()[-1]

print(frontmost)
> 0x38060fd

一旦我們有了視窗 ID,就可以使用 wmctrl 來取得它所屬的應用程式(的 pid):

注意:首先,我們必須為 wmctrl「修復」上面命令的最前面的 id(輸出); wmctrl 和 xprop 的 id 略有不同:

0x381e427 (xprop)
0x0381e427 (wmctrl)

修正上述函數的輸出(使用# [1]or的「最前面」輸出# [2]):

fixed_id = frontmost[:2]+"0"+frontmost[2:]

然後取得最前面視窗(的應用程式)的 pid:

command = "wmctrl -lp"
window_pid = [l.split()[2] for l in subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8").splitlines() if fixed_id in l][0]

> 6262


在 python 2 中,使用 subprocess.Popen():

在 python 2 中,subprocess.check_output 不可用,因此過程略有不同,並且更加詳細:

取得活動視窗(id):

-使用 xprop

# [1]
import subprocess

command = "xprop -root _NET_ACTIVE_WINDOW"                                       
output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
frontmost = output.communicate()[0].decode("utf-8").strip().split()[-1]

print frontmost
> 0x38060fd

使用 wmctrl 和輸出來取得它所屬的應用程式(的 pid)# [1]

-(再次)使用(並修復)以下輸出[1]

# [2]
import subprocess

fixed_id = frontmost[:2]+"0"+frontmost[2:]

command = "wmctrl -lp"
output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
window_pid = [l.split()[2] for l in output.communicate()[0].decode("utf-8").splitlines() if fixed_id in l][0]

print window_pid # pid of the application
> 6262

得到視窗姓名,使用wmctrl和 的輸出# [1] (也使用以機器名稱socket.gethostname()分割輸出)wmctrl

# [3]
import subprocess
import socket

command = "wmctrl -lp"
output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
window_list = output.communicate()[0].decode("utf-8")
window_name = [l for l in window_list.split("\n") if fixed_id in l][0].split(socket.gethostname()+" ")[-1]

print window_name

人xprop
手動控制
曼克斯維特

相關內容