The Python script in the article is really an example of how shell scripts are superior to Python for a lot of jobs.
#!/usr/bin/env python3
import subprocess, random, glob
print('HERE WE GO')
sounds = glob.glob('/Users/{yourName}/Library/Sounds/*.aiff')
sound = random.choice(sounds)
print('randomly selected sound: ', sound)
command = 'defaults write .GlobalPreferences com.apple.sound.beep.sound /Users/{yourName}/Library/Sounds/{}.aiff'.format(sound)
# You could also define an array of sounds yourself,
# if you don't want every .aiff file to be a possibility
# sounds=['tabarnak1', 'tabarnak2', 'tabarnak3']
# sound=random.choice(sounds)
# command = 'defaults write .GlobalPreferences com.apple.sound.beep.sound /Users/{yourName}/Library/Sounds/{}.aiff'.format(sound)
subprocess.call(command, shell=True)
{yourName} could be fixed by using Python’s env or ~ expansion or whatever, but this is much simpler as a shell expansion: ~/Library/Sounds/*.aiff. Using the shell=True flag on subprocess makes the subprocess call totally unsafe and subject to being broken by files with spaces in them anyway. This script is functionally identical but safer:
#!/bin/bash
set -euo pipefail
echo "HERE WE GO"
local FILE=$(ls ~/Library/Sounds/*.aiff | sort --random-sort | head -n 1)
echo "randomly selected sound: $FILE"
defaults write .GlobalPreferences com.apple.sound.beep.sound "$FILE"
The Python script in the article is really an example of how shell scripts are superior to Python for a lot of jobs.
{yourName}
could be fixed by using Python’s env or ~ expansion or whatever, but this is much simpler as a shell expansion:~/Library/Sounds/*.aiff
. Using theshell=True
flag on subprocess makes the subprocess call totally unsafe and subject to being broken by files with spaces in them anyway. This script is functionally identical but safer:can be simplified to
Checked with
GNU shuf
, works even with spaces in filenames, not sure about other implementations.I thought about shuf, but Mac doesn’t have shuf built-in, and this is meant to pick Mac sounds.