[Pkg-mpd-commits] [python-mpd] 228/262: import examples from the old wiki

Simon McVittie smcv at debian.org
Sun May 22 18:16:50 UTC 2016


This is an automated email from the git hooks/post-receive script.

smcv pushed a commit to branch upstream
in repository python-mpd.

commit 1db6747c8dfdac445fc6ae261283194ce626b93a
Author: Jörg Thalheim <joerg at higgsboson.tk>
Date:   Sun Feb 2 10:50:48 2014 +0100

    import examples from the old wiki
---
 examples/errorhandling.py | 136 ++++++++++++++++++++++++++++++++++++++++++++++
 examples/idle.py          |  23 ++++++++
 examples/multitags.py     |  14 +++++
 examples/randomqueue.py   |  36 ++++++++++++
 examples/stats.py         |  73 +++++++++++++++++++++++++
 examples/stickers.py      | 108 ++++++++++++++++++++++++++++++++++++
 examples/summary.txt      |  24 ++++++++
 7 files changed, 414 insertions(+)

diff --git a/examples/errorhandling.py b/examples/errorhandling.py
new file mode 100644
index 0000000..7cef794
--- /dev/null
+++ b/examples/errorhandling.py
@@ -0,0 +1,136 @@
+#! /usr/bin/env python
+#
+#Introduction
+#
+#A python program that continuously polls for song info. Demonstrates how and where to handle errors
+#Details
+#
+
+from mpd import MPDClient, MPDError, CommandError
+import sys
+
+
+class PollerError(Exception):
+    """Fatal error in poller."""
+
+
+class MPDPoller(object):
+    def __init__(self, host="localhost", port="6600", password=None):
+        self._host = host
+        self._port = port
+        self._password = password
+        self._client = MPDClient()
+
+    def connect(self):
+        try:
+            self._client.connect(self._host, self._port)
+        # Catch socket errors
+        except IOError as err:
+            errno, strerror = err
+            raise PollerError("Could not connect to '%s': %s" %
+                              (self._host, strerror))
+
+        # Catch all other possible errors
+        # ConnectionError and ProtocolError are always fatal.  Others may not
+        # be, but we don't know how to handle them here, so treat them as if
+        # they are instead of ignoring them.
+        except MPDError as e:
+            raise PollerError("Could not connect to '%s': %s" %
+                              (self._host, e))
+
+        if self._password:
+            try:
+                self._client.password(self._password)
+
+            # Catch errors with the password command (e.g., wrong password)
+            except CommandError as e:
+                raise PollerError("Could not connect to '%s': "
+                                  "password commmand failed: %s" %
+                                  (self._host, e))
+
+            # Catch all other possible errors
+            except (MPDError, IOError) as e:
+                raise PollerError("Could not connect to '%s': "
+                                  "error with password command: %s" %
+                                  (self._host, e))
+
+    def disconnect(self):
+        # Try to tell MPD we're closing the connection first
+        try:
+            self._client.close()
+
+        # If that fails, don't worry, just ignore it and disconnect
+        except (MPDError, IOError):
+            pass
+
+        try:
+            self._client.disconnect()
+
+        # Disconnecting failed, so use a new client object instead
+        # This should never happen.  If it does, something is seriously broken,
+        # and the client object shouldn't be trusted to be re-used.
+        except (MPDError, IOError):
+            self._client = MPDClient()
+
+    def poll(self):
+        try:
+            song = self._client.currentsong()
+
+        # Couldn't get the current song, so try reconnecting and retrying
+        except (MPDError, IOError):
+            # No error handling required here
+            # Our disconnect function catches all exceptions, and therefore
+            # should never raise any.
+            self.disconnect()
+
+            try:
+                self.connect()
+
+            # Reconnecting failed
+            except PollerError as e:
+                raise PollerError("Reconnecting failed: %s" % e)
+
+            try:
+                song = self._client.currentsong()
+
+            # Failed again, just give up
+            except (MPDError, IOError) as e:
+                raise PollerError("Couldn't retrieve current song: %s" % e)
+
+        # Hurray!  We got the current song without any errors!
+        print(song)
+
+
+def main():
+    from time import sleep
+
+    poller = MPDPoller()
+    poller.connect()
+
+    while True:
+        poller.poll()
+        sleep(3)
+
+
+if __name__ == "__main__":
+    import sys
+
+    try:
+        main()
+
+    # Catch fatal poller errors
+    except PollerError as e:
+        print("Fatal poller error: %s" % e, file=sys.stderr)
+        sys.exit(1)
+
+    # Catch all other non-exit errors
+    except Exception as e:
+        print("Unexpected exception: %s" % e, file=sys.stderr)
+        sys.exit(1)
+
+    # Catch the remaining exit errors
+    except:
+        sys.exit(0)
+
+
+# vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79:
diff --git a/examples/idle.py b/examples/idle.py
new file mode 100644
index 0000000..3bf21d1
--- /dev/null
+++ b/examples/idle.py
@@ -0,0 +1,23 @@
+#idle command
+#
+#cf. official documentation for further details:
+#
+#http://www.musicpd.org/doc/protocol/ch02.html#id525963
+#Example
+
+client.send_idle()
+select([client], [], [])
+changed = client.fetch_idle()
+
+#You can also poll the socket FD (returned by client.fileno(), which is called by default by select, poll, etc.) using other tools too.
+
+#For example, with glib/gobject:
+
+def callback(source, condition):
+   changes = client.fetch_idle()
+   print(changes)
+   return False  # removes the IO watcher
+
+client.send_idle()
+gobject.io_add_watch(client, gobject.IO_IN, callback)
+gobject.MainLoop().run()
diff --git a/examples/multitags.py b/examples/multitags.py
new file mode 100644
index 0000000..c9bb600
--- /dev/null
+++ b/examples/multitags.py
@@ -0,0 +1,14 @@
+#Multi tag files
+#
+#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.
+#
+#When python-mpd encounters the same tag more than once on the same song, it uses a list instead of a string.
+#Function to get a string only song object.
+
+
+def collapse_tags(song):
+   for tag, value in song.iteritems():
+       if isinstance(value, list):
+           song[tag] = ", ".join(set(value))
+
+
diff --git a/examples/randomqueue.py b/examples/randomqueue.py
new file mode 100644
index 0000000..0671d18
--- /dev/null
+++ b/examples/randomqueue.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# IMPORTS
+from mpd import (MPDClient, CommandError)
+from random import choice
+from socket import error as SocketError
+from sys import exit
+
+
+## SETTINGS
+##
+HOST = 'localhost'
+PORT = '6600'
+PASSWORD = False
+###
+
+
+client = MPDClient()
+
+try:
+    client.connect(host=HOST, port=PORT)
+except SocketError:
+    exit(1)
+
+if PASSWORD:
+    try:
+        client.password(PASSWORD)
+    except CommandError:
+        exit(1)
+
+client.add(choice(client.list('file')))
+client.disconnect()
+
+# VIM MODLINE
+# vim: ai ts=4 sw=4 sts=4 expandtab
diff --git a/examples/stats.py b/examples/stats.py
new file mode 100644
index 0000000..77f7c38
--- /dev/null
+++ b/examples/stats.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# IMPORTS
+import sys
+import pprint
+
+from mpd import (MPDClient, CommandError)
+from socket import error as SocketError
+
+HOST = 'localhost'
+PORT = '6600'
+PASSWORD = False
+##
+CON_ID = {'host':HOST, 'port':PORT}
+##  
+
+## Some functions
+def mpdConnect(client, con_id):
+    """
+    Simple wrapper to connect MPD.
+    """
+    try:
+        client.connect(**con_id)
+    except SocketError:
+        return False
+    return True
+
+def mpdAuth(client, secret):
+    """
+    Authenticate
+    """
+    try:
+        client.password(secret)
+    except CommandError:
+        return False
+    return True
+##
+
+def main():
+    ## MPD object instance
+    client = MPDClient()
+    if mpdConnect(client, CON_ID):
+        print('Got connected!')
+    else:
+        print('fail to connect MPD server.')
+        sys.exit(1)
+
+    # Auth if password is set non False
+    if PASSWORD:
+        if mpdAuth(client, PASSWORD):
+            print('Pass auth!')
+        else:
+            print('Error trying to pass auth.')
+            client.disconnect()
+            sys.exit(2)
+
+    ## Fancy output
+    pp = pprint.PrettyPrinter(indent=4)
+
+    ## Print out MPD stats & disconnect
+    print('\nCurrent MPD state:')
+    pp.pprint(client.status())
+
+    print('\nMusic Library stats:')
+    pp.pprint(client.stats())
+
+    client.disconnect()
+    sys.exit(0)
+
+# Script starts here
+if __name__ == "__main__":
+    main()
diff --git a/examples/stickers.py b/examples/stickers.py
new file mode 100644
index 0000000..693c605
--- /dev/null
+++ b/examples/stickers.py
@@ -0,0 +1,108 @@
+#Descriptio, file=sys.stderrn
+#
+#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.
+#Examples
+
+## set sticker "foo" to "bar" on "dir/song.mp3"
+#sticker.py set dir/song.mp3 foo bar
+#
+## get sticker "foo" on "dir/song.mp3"
+#sticker.py get dir/song.mp3 foo
+#
+## list all stickers on "dir/song.mp3"
+#sticker.py list dir/song.mp3
+#
+## find all files with sticker "foo" in "dir"
+#sticker.py find dir foo
+#
+## find all files with sticker "foo"
+#sticker.py find / foo
+#
+## delete sticker "foo" from "dir/song.mp3"
+#sticker.py delete dir/song.mp3 foo
+#
+#sticker.py
+
+#! /usr/bin/env python
+
+# Edit these
+HOST = "localhost"
+PORT = 6600
+PASS = None
+
+
+from optparse import OptionParser
+from socket import error as SocketError
+from sys import stderr
+
+from mpd import MPDClient, MPDError
+
+
+ACTIONS = ("get", "set", "delete", "list", "find")
+
+
+def main(action, uri, name, value):
+    client = MPDClient()
+    client.connect(HOST, PORT)
+    if PASS:
+        client.password(PASS)
+
+    if action == "get":
+        print(client.sticker_get("song", uri, name))
+    if action == "set":
+        client.sticker_set("song", uri, name, value)
+    if action == "delete":
+        client.sticker_delete("song", uri, name)
+    if action == "list":
+        stickers = client.sticker_list("song", uri)
+        for sticker in stickers:
+            print(sticker)
+    if action == "find":
+        matches = client.sticker_find("song", uri, name)
+        for match in matches:
+            if "file" in match:
+                print(match["file"])
+
+
+if __name__ == "__main__":
+    parser = OptionParser(usage="%prog action args", version="0.1",
+                          description="Manipulate and query "
+                                      "MPD song stickers.")
+    options, args = parser.parse_args()
+
+    if len(args) < 1:
+        parser.error("no action specified, must be one of: %s" % " ".join(ACTIONS))
+    action = args.pop(0)
+
+    if action not in ACTIONS:
+        parser.error("action must be one of: %s" % " ".join(ACTIONS))
+
+    if len(args) < 1:
+        parser.error("no URI specified")
+    uri = args.pop(0)
+
+    if action in ("get", "set", "delete", "find"):
+        if len(args) < 1:
+            parser.error("no name specified")
+        name = args.pop(0)
+    else:
+        name = None
+
+    if action == "set":
+        if len(args) < 1:
+            parser.error("no value specified")
+        value = args.pop(0)
+    else:
+        value = None
+
+    try:
+        main(action, uri, name, value)
+    except SocketError as e:
+        print("%s: error with connection to MPD: %s" % \
+                (parser.get_prog_name(), e[1]), file=stderr)
+    except MPDError as e:
+        print("%s: error executing action: %s" % \
+                (parser.get_prog_name(), e), file=stderr)
+
+
+# vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79:
diff --git a/examples/summary.txt b/examples/summary.txt
new file mode 100644
index 0000000..4069017
--- /dev/null
+++ b/examples/summary.txt
@@ -0,0 +1,24 @@
+:Python scripts examples
+
+Here follows some scripts using python-mpd to connect and play with your MPD server.
+
+MPD server used in the script is localhost:6600, please adapt to your own configuration changing the proper var in the script header.
+Examples
+
+    Print out general stats: ExampleStats
+    Random queue: ExampleRandomQueue
+    Handling errors: ExampleErrorhandling
+    Deal with mutli-tag files. Some sound files may define the same tag multiple times, here is a function to deal with it in your client: ExampleMultiTags
+    idle command (python-mpd > 0.3 & mpd > 0.14) ExampleIdle
+    Manipulate and query stickers: ExampleStickers
+
+
+ExampleErrorhandling  demo of handling errors in long-running client
+2010-11-29
+ExampleIdle Using idle command  2010-12-14
+ExampleMultiTags  How to deal with multi tag file 2009-09-15
+ExampleRandomQueue  Queue song at random  2009-09-24
+ExampleStats  Get general information of your MPD server  2009-09-12
+ExampleStickers A command-line client for manipulating and querying stickers
+2010-12-18
+Examples  Some example scripts to show how to play with python-mpd  2010-12-18

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-mpd/python-mpd.git



More information about the Pkg-mpd-commits mailing list