Skip to content

Instantly share code, notes, and snippets.

@qur2
Created June 7, 2013 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qur2/5729056 to your computer and use it in GitHub Desktop.
Save qur2/5729056 to your computer and use it in GitHub Desktop.
Python + AppleScript to bring a window in foreground.
# Using applescript, sets the focus + foreground on a window by its title
# That works on OSX 10.7.5.
# @author Aurelien Scoubeau <aurelien.scoubeau@gmail.com>
import argparse
import subprocess
parser = argparse.ArgumentParser(description='Utility to activate a window by title, for OSX')
parser.add_argument('title', help='Title of the window to activate')
args = vars(parser.parse_args())
title = args['title']
# find the app or window back and activate it
apple = """
set the_title to "%s"
tell application "System Events"
repeat with p in every process whose background only is false
repeat with w in every window of p
if (name of w) is the_title then
tell p
set frontmost to true
perform action "AXRaise" of w
end tell
end if
end repeat
end repeat
end tell
""" % (title,)
p = subprocess.Popen('osascript',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
p.communicate(apple)[0]
# Using AppleScript, lists the title of every window.
# If an hint is given, the list filtered using fuzzy matching.
# That works on OSX 10.7.5.
# @author Aurelien Scoubeau <aurelien.scoubeau@gmail.com>
from fuzzywuzzy import process
import argparse
import subprocess
parser = argparse.ArgumentParser(description='Utility to list window titles, for OSX')
parser.add_argument('hint', help='String to look for in the window titles.')
args = vars(parser.parse_args())
hint = args['hint']
possibilities = []
# app name + window title farming
# it allows listing windows by just typing the app name
apple = """
set window_titles to {}
tell application "System Events"
repeat with p in every process whose background only is false
repeat with w in every window of p
set end of window_titles to (name of p) & "|>" & (name of w)
end repeat
end repeat
end tell
set AppleScript's text item delimiters to "\n"
window_titles as text
"""
p = subprocess.Popen('osascript',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
windows = p.communicate(apple)[0].decode('utf8').split('\n')
if (hint):
# get matches based on script input
windows = [k for k, v in process.extract(hint, windows, limit=10)]
for c in windows:
print c.encode('utf8').split('|>').pop()
@nrwade0
Copy link

nrwade0 commented May 25, 2022

FYI those finding this 2022, I used xfocus.py and had to change apple string to bytes since Popen does not take str arg. Added 2 arguments on line 32: encoding='utf-8', \n text=True). Thanks for posting, qur2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment