Delete Duplicates In MPD Playlist

This is a quick hack in python3 to prune duplicates in the active mpd playlist.
It looks for duplicates by filename. Requires mpc to be installed and respects MPD_HOST and MPD_PORT environment variables.

Sidenote: This is one of my very first python scripts. I am pretty sure this can be done much smarter in python but i am not that skilled yet in that language. So please feel free to improve it. Feedback of any kind is highly appreciated.

import subprocess
data = dict()
delpos = list()
p = subprocess.Popen(["/usr/bin/mpc", "-f", "%position% %file%", "playlist"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout:
 line = line.decode("utf-8")
 line = line.rstrip('\n');
 position, filename = line.split(" ", 1);
for key in data:
 poslen = len(data[key])
 if poslen <= 1: continue
 print("Will delete:", poslen-1, "time(s)", key)
 iterpos = iter(data[key])
 for pos in iterpos:
delpos = list(map(int, delpos))
for item in delpos:
 p = subprocess.Popen(["/usr/bin/mpc", "del", str(item)], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


Copy and paste the code to some file: e.g: /usr/local/bin/
Run it like that:

MPD_HOST="yourpass@yourhost" MPD_PORT="6600" /usr/local/bin/

Leave a Reply

Your email address will not be published / Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.