Skip to content

Instantly share code, notes, and snippets.

@omikun
Created March 2, 2018 07:09
Show Gist options
  • Save omikun/26119e714f66541d69789b2c821e79b4 to your computer and use it in GitHub Desktop.
Save omikun/26119e714f66541d69789b2c821e79b4 to your computer and use it in GitHub Desktop.
Monitors current window under focus and suspends Unity when it is not in focus in order to save battery life
#!/usr/bin/ python
''' This script automatically finds PIDs for Unity
and suspend those processes whenever Unity is not in focus.
This script is meant to stay running and polls window focus every 1 second
Written March 1st, 2018 by Omikun, compiled from StackOverflow answers:
Identify window under focus:
https://superuser.com/questions/734007/how-do-i-tell-which-app-stole-my-focus-in-os-x
Get PID by process name
https://stackoverflow.com/questions/26688936/how-to-get-pid-by-process-name-in-python
'''
from datetime import datetime
from time import sleep
import sys
import subprocess
def get_pid(name):
result = subprocess.check_output(['pgrep Unity'], shell=True)
return result.strip().split('\n')
# if script invoked with an argument, use that as the pid
if len(sys.argv) > 1:
pids = [sys.argv[1]]
else: # otherwise go find all pids associated with Unity
pids = get_pid('Unity')
print "monitoring Unity, with PIDs:", pids,
try:
from AppKit import NSWorkspace
except ImportError:
print "Can't import AppKit -- maybe you're running python from brew?"
print "Try running with Apple's /usr/bin/python instead."
exit(1)
last_active_app = None
stop = True
while True:
active_app = NSWorkspace.sharedWorkspace().activeApplication()
if last_active_app != active_app['NSApplicationName']:
last_active_app = active_app['NSApplicationName']
print "currently focused on", last_active_app
if last_active_app == 'Unity':
print "continuing Unity"
stop = True
for pid in pids:
print subprocess.Popen("kill -CONT " + pid, shell=True)
elif stop:
stop = False
print "stopping unity"
for pid in pids:
print subprocess.Popen("kill -STOP " + pid, shell=True)
sleep(1)
@omikun
Copy link
Author

omikun commented Mar 3, 2018

Updated script in repo

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