Sto cercando di ottenere il titolo della finestra attiva. L'applicazione è un'attività in background, quindi se l'utente ha aperto Eclipse la funzione restituisce "Eclipse - blabla", quindi non ottiene il titolo della finestra della mia finestra. Sto sviluppando questo in Python 2.6 usando PyQt4.Ottenere il titolo della finestra attiva in X
mia soluzione attuale, preso in prestito e leggermente modificato da una vecchia risposta qui a SO, si presenta così:
def get_active_window_title():
title = ''
root_check = ''
root = Popen(['xprop', '-root'], stdout=PIPE)
if root.stdout != root_check:
root_check = root.stdout
for i in root.stdout:
if '_NET_ACTIVE_WINDOW(WINDOW):' in i:
id_ = i.split()[4]
id_w = Popen(['xprop', '-id', id_], stdout=PIPE)
for j in id_w.stdout:
if 'WM_ICON_NAME(STRING)' in j:
if title != j.split()[2]:
return j.split("= ")[1].strip(' \n\"')
Funziona per la maggior parte delle finestre, ma non tutti. Ad esempio, non riesce a trovare le mie finestre di chat di kopete o il nome dell'applicazione che sto attualmente sviluppando.
mio tentativo successivo è simile al seguente:
def get_active_window_title(self):
screen = wnck.screen_get_default()
if screen == None:
return "Could not get screen"
window = screen.get_active_window()
if window == None:
return "Could not get window"
title = window.get_name()
return title;
Ma per qualche motivo finestra è sempre Nessuno.
Qualcuno ha un modo migliore di ottenere il titolo attuale finestra, o come modificare uno dei miei modi, che funziona per tutte le finestre?
Edit:
Nel caso in cui qualcuno è chiedendo questo è il modo che ho trovato che sembra funzionare per tutte le finestre.
def get_active_window_title(self):
root_check = ''
root = Popen(['xprop', '-root'], stdout=PIPE)
if root.stdout != root_check:
root_check = root.stdout
for i in root.stdout:
if '_NET_ACTIVE_WINDOW(WINDOW):' in i:
id_ = i.split()[4]
id_w = Popen(['xprop', '-id', id_], stdout=PIPE)
id_w.wait()
buff = []
for j in id_w.stdout:
buff.append(j)
for line in buff:
match = re.match("WM_NAME\((?P<type>.+)\) = (?P<name>.+)", line)
if match != None:
type = match.group("type")
if type == "STRING" or type == "COMPOUND_TEXT":
return match.group("name")
return "Active window not found"
c'è uno scopo per la copia stdout a root_check se stdout è non vuota? – enthdegree
controlla la soluzione di Alex Spurling più in basso, ha preso quella parte. – dutt