Skip to content

Commit 1db6747

Browse files
committed
import examples from the old wiki
1 parent cfeb3b5 commit 1db6747

7 files changed

+414
-0
lines changed

examples/errorhandling.py

+136
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
#! /usr/bin/env python
2+
#
3+
#Introduction
4+
#
5+
#A python program that continuously polls for song info. Demonstrates how and where to handle errors
6+
#Details
7+
#
8+
9+
from mpd import MPDClient, MPDError, CommandError
10+
import sys
11+
12+
13+
class PollerError(Exception):
14+
"""Fatal error in poller."""
15+
16+
17+
class MPDPoller(object):
18+
def __init__(self, host="localhost", port="6600", password=None):
19+
self._host = host
20+
self._port = port
21+
self._password = password
22+
self._client = MPDClient()
23+
24+
def connect(self):
25+
try:
26+
self._client.connect(self._host, self._port)
27+
# Catch socket errors
28+
except IOError as err:
29+
errno, strerror = err
30+
raise PollerError("Could not connect to '%s': %s" %
31+
(self._host, strerror))
32+
33+
# Catch all other possible errors
34+
# ConnectionError and ProtocolError are always fatal. Others may not
35+
# be, but we don't know how to handle them here, so treat them as if
36+
# they are instead of ignoring them.
37+
except MPDError as e:
38+
raise PollerError("Could not connect to '%s': %s" %
39+
(self._host, e))
40+
41+
if self._password:
42+
try:
43+
self._client.password(self._password)
44+
45+
# Catch errors with the password command (e.g., wrong password)
46+
except CommandError as e:
47+
raise PollerError("Could not connect to '%s': "
48+
"password commmand failed: %s" %
49+
(self._host, e))
50+
51+
# Catch all other possible errors
52+
except (MPDError, IOError) as e:
53+
raise PollerError("Could not connect to '%s': "
54+
"error with password command: %s" %
55+
(self._host, e))
56+
57+
def disconnect(self):
58+
# Try to tell MPD we're closing the connection first
59+
try:
60+
self._client.close()
61+
62+
# If that fails, don't worry, just ignore it and disconnect
63+
except (MPDError, IOError):
64+
pass
65+
66+
try:
67+
self._client.disconnect()
68+
69+
# Disconnecting failed, so use a new client object instead
70+
# This should never happen. If it does, something is seriously broken,
71+
# and the client object shouldn't be trusted to be re-used.
72+
except (MPDError, IOError):
73+
self._client = MPDClient()
74+
75+
def poll(self):
76+
try:
77+
song = self._client.currentsong()
78+
79+
# Couldn't get the current song, so try reconnecting and retrying
80+
except (MPDError, IOError):
81+
# No error handling required here
82+
# Our disconnect function catches all exceptions, and therefore
83+
# should never raise any.
84+
self.disconnect()
85+
86+
try:
87+
self.connect()
88+
89+
# Reconnecting failed
90+
except PollerError as e:
91+
raise PollerError("Reconnecting failed: %s" % e)
92+
93+
try:
94+
song = self._client.currentsong()
95+
96+
# Failed again, just give up
97+
except (MPDError, IOError) as e:
98+
raise PollerError("Couldn't retrieve current song: %s" % e)
99+
100+
# Hurray! We got the current song without any errors!
101+
print(song)
102+
103+
104+
def main():
105+
from time import sleep
106+
107+
poller = MPDPoller()
108+
poller.connect()
109+
110+
while True:
111+
poller.poll()
112+
sleep(3)
113+
114+
115+
if __name__ == "__main__":
116+
import sys
117+
118+
try:
119+
main()
120+
121+
# Catch fatal poller errors
122+
except PollerError as e:
123+
print("Fatal poller error: %s" % e, file=sys.stderr)
124+
sys.exit(1)
125+
126+
# Catch all other non-exit errors
127+
except Exception as e:
128+
print("Unexpected exception: %s" % e, file=sys.stderr)
129+
sys.exit(1)
130+
131+
# Catch the remaining exit errors
132+
except:
133+
sys.exit(0)
134+
135+
136+
# vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79:

examples/idle.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#idle command
2+
#
3+
#cf. official documentation for further details:
4+
#
5+
#http://www.musicpd.org/doc/protocol/ch02.html#id525963
6+
#Example
7+
8+
client.send_idle()
9+
select([client], [], [])
10+
changed = client.fetch_idle()
11+
12+
#You can also poll the socket FD (returned by client.fileno(), which is called by default by select, poll, etc.) using other tools too.
13+
14+
#For example, with glib/gobject:
15+
16+
def callback(source, condition):
17+
changes = client.fetch_idle()
18+
print(changes)
19+
return False # removes the IO watcher
20+
21+
client.send_idle()
22+
gobject.io_add_watch(client, gobject.IO_IN, callback)
23+
gobject.MainLoop().run()

examples/multitags.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#Multi tag files
2+
#
3+
#Some tag formats (such as ID3v2 and VorbisComment) support defining the same tag multiple times, mostly for when a song has multiple artists. MPD supports this, and sends each occurrence of a tag to the client.
4+
#
5+
#When python-mpd encounters the same tag more than once on the same song, it uses a list instead of a string.
6+
#Function to get a string only song object.
7+
8+
9+
def collapse_tags(song):
10+
for tag, value in song.iteritems():
11+
if isinstance(value, list):
12+
song[tag] = ", ".join(set(value))
13+
14+

examples/randomqueue.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# IMPORTS
5+
from mpd import (MPDClient, CommandError)
6+
from random import choice
7+
from socket import error as SocketError
8+
from sys import exit
9+
10+
11+
## SETTINGS
12+
##
13+
HOST = 'localhost'
14+
PORT = '6600'
15+
PASSWORD = False
16+
###
17+
18+
19+
client = MPDClient()
20+
21+
try:
22+
client.connect(host=HOST, port=PORT)
23+
except SocketError:
24+
exit(1)
25+
26+
if PASSWORD:
27+
try:
28+
client.password(PASSWORD)
29+
except CommandError:
30+
exit(1)
31+
32+
client.add(choice(client.list('file')))
33+
client.disconnect()
34+
35+
# VIM MODLINE
36+
# vim: ai ts=4 sw=4 sts=4 expandtab

examples/stats.py

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# IMPORTS
5+
import sys
6+
import pprint
7+
8+
from mpd import (MPDClient, CommandError)
9+
from socket import error as SocketError
10+
11+
HOST = 'localhost'
12+
PORT = '6600'
13+
PASSWORD = False
14+
##
15+
CON_ID = {'host':HOST, 'port':PORT}
16+
##
17+
18+
## Some functions
19+
def mpdConnect(client, con_id):
20+
"""
21+
Simple wrapper to connect MPD.
22+
"""
23+
try:
24+
client.connect(**con_id)
25+
except SocketError:
26+
return False
27+
return True
28+
29+
def mpdAuth(client, secret):
30+
"""
31+
Authenticate
32+
"""
33+
try:
34+
client.password(secret)
35+
except CommandError:
36+
return False
37+
return True
38+
##
39+
40+
def main():
41+
## MPD object instance
42+
client = MPDClient()
43+
if mpdConnect(client, CON_ID):
44+
print('Got connected!')
45+
else:
46+
print('fail to connect MPD server.')
47+
sys.exit(1)
48+
49+
# Auth if password is set non False
50+
if PASSWORD:
51+
if mpdAuth(client, PASSWORD):
52+
print('Pass auth!')
53+
else:
54+
print('Error trying to pass auth.')
55+
client.disconnect()
56+
sys.exit(2)
57+
58+
## Fancy output
59+
pp = pprint.PrettyPrinter(indent=4)
60+
61+
## Print out MPD stats & disconnect
62+
print('\nCurrent MPD state:')
63+
pp.pprint(client.status())
64+
65+
print('\nMusic Library stats:')
66+
pp.pprint(client.stats())
67+
68+
client.disconnect()
69+
sys.exit(0)
70+
71+
# Script starts here
72+
if __name__ == "__main__":
73+
main()

examples/stickers.py

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#Descriptio, file=sys.stderrn
2+
#
3+
#Using this client, one can manipulate and query stickers. The script is essentially a raw interface to the MPD protocol's sticker command, and is used in exactly the same way.
4+
#Examples
5+
6+
## set sticker "foo" to "bar" on "dir/song.mp3"
7+
#sticker.py set dir/song.mp3 foo bar
8+
#
9+
## get sticker "foo" on "dir/song.mp3"
10+
#sticker.py get dir/song.mp3 foo
11+
#
12+
## list all stickers on "dir/song.mp3"
13+
#sticker.py list dir/song.mp3
14+
#
15+
## find all files with sticker "foo" in "dir"
16+
#sticker.py find dir foo
17+
#
18+
## find all files with sticker "foo"
19+
#sticker.py find / foo
20+
#
21+
## delete sticker "foo" from "dir/song.mp3"
22+
#sticker.py delete dir/song.mp3 foo
23+
#
24+
#sticker.py
25+
26+
#! /usr/bin/env python
27+
28+
# Edit these
29+
HOST = "localhost"
30+
PORT = 6600
31+
PASS = None
32+
33+
34+
from optparse import OptionParser
35+
from socket import error as SocketError
36+
from sys import stderr
37+
38+
from mpd import MPDClient, MPDError
39+
40+
41+
ACTIONS = ("get", "set", "delete", "list", "find")
42+
43+
44+
def main(action, uri, name, value):
45+
client = MPDClient()
46+
client.connect(HOST, PORT)
47+
if PASS:
48+
client.password(PASS)
49+
50+
if action == "get":
51+
print(client.sticker_get("song", uri, name))
52+
if action == "set":
53+
client.sticker_set("song", uri, name, value)
54+
if action == "delete":
55+
client.sticker_delete("song", uri, name)
56+
if action == "list":
57+
stickers = client.sticker_list("song", uri)
58+
for sticker in stickers:
59+
print(sticker)
60+
if action == "find":
61+
matches = client.sticker_find("song", uri, name)
62+
for match in matches:
63+
if "file" in match:
64+
print(match["file"])
65+
66+
67+
if __name__ == "__main__":
68+
parser = OptionParser(usage="%prog action args", version="0.1",
69+
description="Manipulate and query "
70+
"MPD song stickers.")
71+
options, args = parser.parse_args()
72+
73+
if len(args) < 1:
74+
parser.error("no action specified, must be one of: %s" % " ".join(ACTIONS))
75+
action = args.pop(0)
76+
77+
if action not in ACTIONS:
78+
parser.error("action must be one of: %s" % " ".join(ACTIONS))
79+
80+
if len(args) < 1:
81+
parser.error("no URI specified")
82+
uri = args.pop(0)
83+
84+
if action in ("get", "set", "delete", "find"):
85+
if len(args) < 1:
86+
parser.error("no name specified")
87+
name = args.pop(0)
88+
else:
89+
name = None
90+
91+
if action == "set":
92+
if len(args) < 1:
93+
parser.error("no value specified")
94+
value = args.pop(0)
95+
else:
96+
value = None
97+
98+
try:
99+
main(action, uri, name, value)
100+
except SocketError as e:
101+
print("%s: error with connection to MPD: %s" % \
102+
(parser.get_prog_name(), e[1]), file=stderr)
103+
except MPDError as e:
104+
print("%s: error executing action: %s" % \
105+
(parser.get_prog_name(), e), file=stderr)
106+
107+
108+
# vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79:

0 commit comments

Comments
 (0)