Control Spotify from the command line

I am often working on something, only to get distracted by a terrible track which was selected through related artists, or Spotify radio. This does not happen too often, but it does happen and I would like a quick way to skip the track without having to mess with the GUI. I searched online for something that could do this but after half an hour I had still not found anything.

To get this working, you need to install xdotool. You will also need Python installed.

This example will be for linux, but should work fine on any unix like system.

sudo pacman -S xdotool

Once that is done, you can copy the script below and place it somewhere in your path. Mine resides in ~/bin/spotify.py

import subprocess
import sys

def sendkeys(*keys):
	subprocess.call(['xdotool', 'search', '--name', 'Spotify Premium - Linux Preview', 'key'] + list(keys))
	return "ok\n"

if sys.argv[1] == 'n':
	sendkeys('ctrl+Right')
elif sys.argv[1] == 'p':
	sendkeys('ctrl+Left')

Make sure to give it executable permissions.

chmod +x ~/bin/spotify.py

So you would envoke this from the command line as follows:

python ~/bin/spotify.py

As an additional convenience, you can alias this to a shortcut.

echo "alias n='python ~/bin/spotify.py n'" >> ~/.bash_aliases
echo "alias p='python ~/bin/spotify.py p'" >> ~/.bash_aliases

Reload your shell, and you should be able to press n, or p followed by enter to skip tracks.


March 1, 2013