Found a more reliable solution with AppleScript:
-- it looks like it needs to execute twice to work reliably.
changeKeyboardLayout("Squirrel")
changeKeyboardLayout("Squirrel")
on changeKeyboardLayout(layoutName)
tell application "System Events" to ¬
tell application process "TextInputMenuAgent" to ¬
tell menu bar item 1 of menu bar 2
click
delay 0.1
click menu item layoutName of menu 1
end tell
end changeKeyboardLayout