Skip to content

Instantly share code, notes, and snippets.

@ohaiibuzzle
Last active March 17, 2024 21:00
Show Gist options
  • Save ohaiibuzzle/60ed8eb61a6d2657cb66bf2732fcfde6 to your computer and use it in GitHub Desktop.
Save ohaiibuzzle/60ed8eb61a6d2657cb66bf2732fcfde6 to your computer and use it in GitHub Desktop.
macOS USB Notifier
#!/usr/bin/env python3
import subprocess
import plistlib
import time
def send_notification(title, message, sound=None):
command = 'display notification "{}" with title "{}" sound name "{}"'\
.format(message, title, sound) \
if sound else 'display notification "{}" with title "{}"'\
.format(message, title)
subprocess.call(['osascript', '-e', command])
def get_devices():
devices = subprocess.check_output(['system_profiler',
'SPUSBDataType',
'-xml'])
return plistlib.loads(devices)[0]
def enumerate_devices(system_profiler_output=None):
if system_profiler_output is None:
system_profiler_output = get_devices()
devices = []
# If the device has sub devices, recurse into them
if '_items' in system_profiler_output:
for item in system_profiler_output['_items']:
devices.extend(enumerate_devices(item))
# Else print device[manufacturer] (if possible) and device[product]
else:
if 'manufacturer' in system_profiler_output:
devices.append(system_profiler_output['manufacturer']
+ ' '
+ system_profiler_output['_name'])
else:
devices.append(system_profiler_output['_name'])
return devices
def main():
last_device_list = enumerate_devices()
while True:
time.sleep(1)
device_list = enumerate_devices()
if device_list == last_device_list: # we don't care:tm:
continue
connected_devices = list(set(device_list) - set(last_device_list))
disconnected_devices = list(set(last_device_list) - set(device_list))
for device in connected_devices:
send_notification('USB Device Connected', device, 'Hero')
for device in disconnected_devices:
send_notification('USB Device Disconnected', device, 'Pop')
last_device_list = device_list
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment