1 .. SPDX-FileCopyrightText: 2018-2023 kaliko <kaliko@azylum.org>
2 .. SPDX-License-Identifier: LGPL-3.0-or-later
4 Using the client library
5 =========================
10 The client library can be used as follows:
12 .. code-block:: python
14 client = musicpd.MPDClient() # create client object
15 client.connect() # use MPD_HOST/MPD_PORT if set else
16 # test ${XDG_RUNTIME_DIR}/mpd/socket for existence
17 # fallback to localhost:6600
18 # connect support host/port argument as well
19 print(client.mpd_version) # print the MPD protocol version
20 client.setvol('42') # sets the volume
21 client.disconnect() # disconnect from the server
23 The MPD command protocol exchanges line-based text records. The client emits a
24 command with optional arguments. In the example above the client sends a
25 `setvol` command with the string argument `42`.
27 MPD commands are exposed as :py:class:`musicpd.MPDClient` methods. Methods
28 **arguments are python strings**. Some commands are composed of more than one word
29 (ie "**tagtypes [disable|enable|all]**"), for these use a `snake case`_ style to
30 access the method. Then **"tagtypes enable"** command is called with
31 **"tagtypes_enable"**.
33 Remember MPD protocol is text based, then all MPD command arguments are UTF-8
34 strings. In the example above, an integer can be used as argument for the
35 `setvol` command, but it is then evaluated as a string when the command is
36 written to the socket. To avoid confusion use regular string instead of relying
37 on object string representation.
39 :py:class:`musicpd.MPDClient` methods returns different kinds of objects
40 depending on the command. Could be :py:obj:`None`, a single object as a
41 :py:obj:`str` or a :py:obj:`dict`, a list of :py:obj:`dict`.
43 Then :py:class:`musicpd.MPDClient` **methods signatures** are not hard coded
44 within this module since the protocol is handled on the server side. Please
45 refer to the protocol and MPD commands in `MPD protocol documentation`_ to
46 learn how to call commands and what kind of arguments they expect.
48 Some examples are provided for the most common cases, see :ref:`examples`.
50 For a list of currently supported commands in this python module see
53 .. _environment_variables:
58 :py:class:`musicpd.MPDClient` honors the following environment variables:
62 MPD host (:abbr:`FQDN (fully qualified domain name)`, IP, socket path or abstract socket) and password.
64 | To define a **password** set :envvar:`MPD_HOST` to "*password@host*" (password only "*password@*")
65 | For **abstract socket** use "@" as prefix : "*@socket*" and then with a password "*pass@@socket*"
66 | Regular **unix socket** are set with an absolute path: "*/run/mpd/socket*"
70 MPD port, relevant for TCP socket only
72 .. envvar:: MPD_TIMEOUT
74 socket timeout when connecting to MPD and waiting for MPD’s response (in seconds)
76 .. envvar:: XDG_RUNTIME_DIR
78 path to look for potential socket
86 * use :envvar:`MPD_HOST` environment variable if set, extract password if present,
87 * else use :envvar:`XDG_RUNTIME_DIR` to looks for an existing file in ``${XDG_RUNTIME_DIR}/mpd/socket``, :envvar:`XDG_RUNTIME_DIR` defaults to ``/run`` if not set.
88 * else set host to ``localhost``
91 * use :envvar:`MPD_PORT` environment variable if set
95 * use :envvar:`MPD_TIMEOUT` if set
96 * else use :py:obj:`musicpd.CONNECTION_TIMEOUT`
101 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
102 transparently called with :ref:`default setting<default_settings>` (use
103 :ref:`environment variables<environment_variables>` to override defaults).
104 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
106 .. code-block:: python
109 os.environ['MPD_HOST'] = 'mpdhost'
110 with MPDClient() as c:
117 Command lists are also supported using `command_list_ok_begin()` and
118 `command_list_end()` :
120 .. code-block:: python
122 client.command_list_ok_begin() # start a command list
123 client.update() # insert the update command into the list
124 client.status() # insert the status command into the list
125 results = client.command_list_end() # results will be a list with the results
130 Some commands (e.g. delete) allow specifying a range in the form `"START:END"` (cf. `MPD protocol documentation`_ for more details).
132 Possible ranges are: `"START:END"`, `"START:"` and `":"` :
134 Instead of giving the plain string as `"START:END"`, you **can** provide a :py:obj:`tuple` as `(START,END)`. The module is then ensuring the format is correct and raises an :py:obj:`musicpd.CommandError` exception otherwise. Empty start or end can be specified as en empty string ``''`` or :py:obj:`None`.
136 .. code-block:: python
138 # An intelligent clear
139 # clears played track in the queue, currentsong included
140 pos = client.currentsong().get('pos', 0)
141 # the range object accepts str, no need to convert to int
142 client.delete((0, pos))
143 # missing end interpreted as highest value possible, pay attention still need a tuple.
144 client.delete((pos,)) # purge queue from current to the end
146 A notable case is the *rangeid* command allowing an empty range specified
147 as a single colon as argument (i.e. sending just ``":"``):
149 .. code-block:: python
151 # sending "rangeid :" to clear the range, play everything
152 client.rangeid(()) # send an empty tuple
154 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
156 .. note:: Remember the use of a tuple is **optional**. Range can still be specified as a plain string ``"START:END"``.
161 Commands may also return iterators instead of lists if `iterate` is set to
164 .. code-block:: python
166 client.iterate = True
167 for song in client.playlistinfo():
170 Idle prefixed commands
171 ----------------------
173 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
174 send a MPD command and then fetch the result later (non-blocking call).
175 This is useful for the idle command:
177 .. code-block:: python
179 >>> client.send_idle()
180 # do something else or use function like select()
181 # http://docs.python.org/howto/sockets.html#non-blocking-sockets
182 # ex. select([client], [], [])
183 >>> events = client.fetch_idle()
185 # more complex use for example, with glib/gobject:
186 >>> def callback(source, condition):
187 >>> changes = client.fetch_idle()
189 >>> return False # removes the IO watcher
191 >>> client.send_idle()
192 >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
193 >>> gobject.MainLoop().run()
195 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
197 Fetching binary content (cover art)
198 -----------------------------------
200 Fetching album covers is possible with albumart, here is an example:
202 .. code-block:: python
204 >>> cli = musicpd.MPDClient()
206 >>> track = "Steve Reich/1978-Music for 18 Musicians"
207 >>> aart = cli.albumart(track, 0)
208 >>> received = int(aart.get('binary'))
209 >>> size = int(aart.get('size'))
210 >>> with open('/tmp/cover', 'wb') as cover:
211 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
212 >>> cover.write(aart.get('data'))
213 >>> while received < size:
214 >>> aart = cli.albumart(track, received)
215 >>> cover.write(aart.get('data'))
216 >>> received += int(aart.get('binary'))
217 >>> if received != size:
218 >>> print('something went wrong', file=sys.stderr)
221 A :py:obj:`musicpd.CommandError` is raised if the album does not expose a cover.
223 You can also use `readpicture` command to fetch embedded picture:
225 .. code-block:: python
227 >>> cli = musicpd.MPDClient()
229 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
230 >>> rpict = cli.readpicture(track, 0)
232 >>> print('No embedded picture found', file=sys.stderr)
234 >>> size = int(rpict['size'])
235 >>> done = int(rpict['binary'])
236 >>> with open('/tmp/cover', 'wb') as cover:
237 >>> cover.write(rpict['data'])
238 >>> while size > done:
239 >>> rpict = cli.readpicture(track, done)
240 >>> done += int(rpict['binary'])
241 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
242 >>> cover.write(rpict['data'])
245 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
253 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
255 A timeout is used for the initial MPD connection (``connect`` command), then
256 the socket is put in blocking mode with no timeout. Its value is set in
257 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
258 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
259 is possible to set socket timeout for all command setting
260 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
262 Having ``socket_timeout`` enabled can help to detect "half-open connection".
263 For instance loosing connectivity without the server explicitly closing the
264 connection (switching network interface ethernet/wifi, router down, etc…).
266 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
267 timeout. A couple of seconds should be enough for commands to complete except
268 for the special case of ``idle`` command which by definition *“ waits until
269 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
270 protocol documentation`_).
272 Here is a solution to use ``idle`` command with ``socket_timeout``:
274 .. code-block:: python
280 cli = musicpd.MPDClient()
282 cli.socket_timeout = 10 # seconds
283 select_timeout = 5 # second
286 cli.send_idle() # use send_ API to avoid blocking on read
287 _read, _, _ = select.select([cli], [], [], select_timeout)
288 if _read: # tries to read response
289 ret = cli.fetch_idle()
290 print(', '.join(ret)) # Do something
293 except socket.timeout as err:
294 print(f'{err} (timeout {cli.socket_timeout})')
295 except (OSError, musicpd.MPDError) as err:
297 if cli._sock is not None:
299 except KeyboardInterrupt:
304 * First launch a non blocking ``idle`` command. This call do not wait for a
305 response to avoid socket timeout waiting for an MPD event.
306 * ``select`` waits for something to read on the socket (the idle response
307 in this case), returns after ``select_timeout`` seconds anyway.
308 * In case there is something to read read it using ``fetch_idle``
309 * Nothing to read, cancel idle with ``noidle``
311 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
312 triggering a socket timeout unless the connection is actually lost (actually it
313 could also be that MPD took too much time to answer, but MPD taking more than a
314 couple of seconds for these commands should never occur).
321 The :py:obj:`connect<musicpd.MPDClient.connect>` method raises
322 :py:obj:`ConnectionError<musicpd.ConnectionError>` only (an :py:obj:`MPDError<musicpd.MPDError>` exception) but then, calling other MPD commands, the module can raise
323 :py:obj:`MPDError<musicpd.MPDError>` or an :py:obj:`OSError` depending on the error and
326 Then using musicpd module both :py:obj:`musicpd.MPDError` and :py:obj:`OSError`
327 exceptions families are expected, see :ref:`examples<exceptions_example>` for a
328 way to deal with this.
330 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
331 .. _snake case: https://en.wikipedia.org/wiki/Snake_case
332 .. vim: spell spelllang=en