1 Using the client library
2 =========================
7 The client library can be used as follows:
11 client = musicpd.MPDClient() # create client object
12 client.connect() # use MPD_HOST/MPD_PORT if set else
13 # test ${XDG_RUNTIME_DIR}/mpd/socket for existence
14 # fallback to localhost:6600
15 # connect support host/port argument as well
16 print(client.mpd_version) # print the mpd protocol version
17 print(client.cmd('foo', 42)) # print result of the request "cmd foo 42"
18 # (nb. for actual command, see link to the protocol below)
19 client.disconnect() # disconnect from the server
21 In the example above `cmd` in not an actual MPD command, for a list of
22 supported commands, their arguments (as MPD currently understands
23 them), and the functions used to parse their responses see :ref:`commands`.
25 See the `MPD protocol documentation`_ for more details.
27 .. _environment_variables:
32 The client honors the following environment variables:
34 * ``MPD_HOST`` MPD host (:abbr:`FQDN (fully qualified domain name)`, socket path or abstract socket) and password.
36 | To define a password set MPD_HOST to "`password@host`" (password only "`password@`")
37 | For abstract socket use "@" as prefix : "`@socket`" and then with a password "`pass@@socket`"
38 | Regular unix socket are set with an absolute path: "`/run/mpd/socket`"
39 * ``MPD_PORT`` MPD port, relevant for TCP socket only, ie with :abbr:`FQDN (fully qualified domain name)` defined host
40 * ``MPD_TIMEOUT`` timeout for connecting to MPD and waiting for MPD’s response in seconds
41 * ``XDG_RUNTIME_DIR`` path to look for potential socket: ``${XDG_RUNTIME_DIR}/mpd/socket``
48 * If ``MPD_HOST`` is not set, then look for a socket in ``${XDG_RUNTIME_DIR}/mpd/socket``
49 * If there is no socket use ``localhost``
50 * If ``MPD_PORT`` is not set, then use ``6600``
51 * If ``MPD_TIMEOUT`` is not set, then uses :py:obj:`musicpd.CONNECTION_TIMEOUT`
57 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
58 transparently called with :ref:`default setting<default_settings>` (use
59 :ref:`environment variables<environment_variables>` to override defaults).
60 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
62 .. code-block:: python
65 os.environ['MPD_HOST'] = 'mpdhost'
66 with MPDClient() as c:
73 Command lists are also supported using `command_list_ok_begin()` and
74 `command_list_end()` :
76 .. code-block:: python
78 client.command_list_ok_begin() # start a command list
79 client.update() # insert the update command into the list
80 client.status() # insert the status command into the list
81 results = client.command_list_end() # results will be a list with the results
86 Provide a 2-tuple as argument for command supporting ranges (cf. `MPD protocol documentation`_ for more details).
87 Possible ranges are: "START:END", "START:" and ":" :
89 .. code-block:: python
91 # An intelligent clear
92 # clears played track in the queue, currentsong included
93 pos = client.currentsong().get('pos', 0)
94 # the 2-tuple range object accepts str, no need to convert to int
95 client.delete((0, pos))
96 # missing end interpreted as highest value possible, pay attention still need a tuple.
97 client.delete((pos,)) # purge queue from current to the end
99 A notable case is the `rangeid` command allowing an empty range specified
100 as a single colon as argument (i.e. sending just ":"):
102 .. code-block:: python
104 # sending "rangeid :" to clear the range, play everything
105 client.rangeid(()) # send an empty tuple
107 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
112 Commands may also return iterators instead of lists if `iterate` is set to
115 .. code-block:: python
117 client.iterate = True
118 for song in client.playlistinfo():
121 Idle prefixed commands
122 ----------------------
124 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
125 send a MPD command and then fetch the result later.
126 This is useful for the idle command:
128 .. code-block:: python
130 >>> client.send_idle()
131 # do something else or use function like select()
132 # http://docs.python.org/howto/sockets.html#non-blocking-sockets
133 # ex. select([client], [], [])
134 >>> events = client.fetch_idle()
136 # more complex use for example, with glib/gobject:
137 >>> def callback(source, condition):
138 >>> changes = client.fetch_idle()
140 >>> return False # removes the IO watcher
142 >>> client.send_idle()
143 >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
144 >>> gobject.MainLoop().run()
146 Fetching binary content (cover art)
147 -----------------------------------
149 Fetching album covers is possible with albumart, here is an example:
151 .. code-block:: python
153 >>> cli = musicpd.MPDClient()
155 >>> track = "Steve Reich/1978-Music for 18 Musicians"
156 >>> aart = cli.albumart(track, 0)
157 >>> received = int(aart.get('binary'))
158 >>> size = int(aart.get('size'))
159 >>> with open('/tmp/cover', 'wb') as cover:
160 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
161 >>> cover.write(aart.get('data'))
162 >>> while received < size:
163 >>> aart = cli.albumart(track, received)
164 >>> cover.write(aart.get('data'))
165 >>> received += int(aart.get('binary'))
166 >>> if received != size:
167 >>> print('something went wrong', file=sys.stderr)
170 A `CommandError` is raised if the album does not expose a cover.
172 You can also use `readpicture` command to fetch embedded picture:
174 .. code-block:: python
176 >>> cli = musicpd.MPDClient()
178 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
179 >>> rpict = cli.readpicture(track, 0)
181 >>> print('No embedded picture found', file=sys.stderr)
183 >>> size = int(rpict['size'])
184 >>> done = int(rpict['binary'])
185 >>> with open('/tmp/cover', 'wb') as cover:
186 >>> cover.write(rpict['data'])
187 >>> while size > done:
188 >>> rpict = cli.readpicture(track, done)
189 >>> done += int(rpict['binary'])
190 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
191 >>> cover.write(rpict['data'])
194 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
200 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
202 A timeout is used for the initial MPD connection (``connect`` command), then
203 the socket is put in blocking mode with no timeout. Its value is set in
204 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
205 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
206 is possible to set socket timeout for all command setting
207 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
209 Having ``socket_timeout`` enabled can help to detect "half-open connection".
210 For instance loosing connectivity without the server explicitly closing the
211 connection (switching network interface ethernet/wifi, router down, etc…).
213 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
214 timeout. A couple of seconds should be enough for commands to complete except
215 for the special case of ``idle`` command which by definition *“ waits until
216 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
217 protocol documentation`_).
219 Here is a solution to use ``idle`` command with ``socket_timeout``:
221 .. code-block:: python
227 cli = musicpd.MPDClient()
229 cli.socket_timeout = 10 # seconds
230 select_timeout = 5 # second
233 cli.send_idle() # use send_ API to avoid blocking on read
234 _read, _, _ = select.select([cli], [], [], select_timeout)
235 if _read: # tries to read response
236 ret = cli.fetch_idle()
237 print(', '.join(ret)) # Do something
240 except socket.timeout as err:
241 print(f'{err} (timeout {cli.socket_timeout})')
242 except (OSError, musicpd.MPDError) as err:
244 if cli._sock is not None:
246 except KeyboardInterrupt:
251 * First launch a non blocking ``idle`` command. This call do not wait for a
252 response to avoid socket timeout waiting for an MPD event.
253 * ``select`` waits for something to read on the socket (the idle response
254 in this case), returns after ``select_timeout`` seconds anyway.
255 * In case there is something to read read it using ``fetch_idle``
256 * Nothing to read, cancel idle with ``noidle``
258 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
259 triggering a socket timeout unless the connection is actually lost (actually it
260 could also be that MPD took to much time to answer, but MPD taking more than a
261 couple of seconds for these commands should never occur).
264 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
265 .. vim: spell spelllang=en