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 depending on the command. Could be :py:obj:`None`, a single object as a :py:obj:`str` or a :py:obj:`dict`, a list of :py:obj:`dict`.
41 For more about the protocol and MPD commands see the `MPD protocol
44 For a list of currently supported commands in this python module see
47 .. _environment_variables:
52 :py:class:`musicpd.MPDClient` honors the following environment variables:
56 MPD host (:abbr:`FQDN (fully qualified domain name)`, IP, socket path or abstract socket) and password.
58 | To define a **password** set :envvar:`MPD_HOST` to "*password@host*" (password only "*password@*")
59 | For **abstract socket** use "@" as prefix : "*@socket*" and then with a password "*pass@@socket*"
60 | Regular **unix socket** are set with an absolute path: "*/run/mpd/socket*"
64 MPD port, relevant for TCP socket only
66 .. envvar:: MPD_TIMEOUT
68 socket timeout when connecting to MPD and waiting for MPD’s response (in seconds)
70 .. envvar:: XDG_RUNTIME_DIR
72 path to look for potential socket
80 * use :envvar:`MPD_HOST` environment variable if set, extract password if present,
81 * else looks for an existing file in :envvar:`${XDG_RUNTIME_DIR:-/run/}/mpd/socket`
82 * else set host to ``localhost``
85 * use :envvar:`MPD_PORT` environment variable is set
89 * use :envvar:`MPD_TIMEOUT` is set
90 * else use :py:obj:`musicpd.CONNECTION_TIMEOUT`
95 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
96 transparently called with :ref:`default setting<default_settings>` (use
97 :ref:`environment variables<environment_variables>` to override defaults).
98 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
100 .. code-block:: python
103 os.environ['MPD_HOST'] = 'mpdhost'
104 with MPDClient() as c:
111 Command lists are also supported using `command_list_ok_begin()` and
112 `command_list_end()` :
114 .. code-block:: python
116 client.command_list_ok_begin() # start a command list
117 client.update() # insert the update command into the list
118 client.status() # insert the status command into the list
119 results = client.command_list_end() # results will be a list with the results
124 Some commands (e.g. delete) allow specifying a range in the form `"START:END"` (cf. `MPD protocol documentation`_ for more details).
126 Possible ranges are: `"START:END"`, `"START:"` and `":"` :
128 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`.
130 .. code-block:: python
132 # An intelligent clear
133 # clears played track in the queue, currentsong included
134 pos = client.currentsong().get('pos', 0)
135 # the range object accepts str, no need to convert to int
136 client.delete((0, pos))
137 # missing end interpreted as highest value possible, pay attention still need a tuple.
138 client.delete((pos,)) # purge queue from current to the end
140 A notable case is the *rangeid* command allowing an empty range specified
141 as a single colon as argument (i.e. sending just ``":"``):
143 .. code-block:: python
145 # sending "rangeid :" to clear the range, play everything
146 client.rangeid(()) # send an empty tuple
148 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
150 .. note:: Remember the use of a tuple is **optional**. Range can still be specified as a plain string ``"START:END"``.
155 Commands may also return iterators instead of lists if `iterate` is set to
158 .. code-block:: python
160 client.iterate = True
161 for song in client.playlistinfo():
164 Idle prefixed commands
165 ----------------------
167 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
168 send a MPD command and then fetch the result later (non-blocking call).
169 This is useful for the idle command:
171 .. code-block:: python
173 >>> client.send_idle()
174 # do something else or use function like select()
175 # http://docs.python.org/howto/sockets.html#non-blocking-sockets
176 # ex. select([client], [], [])
177 >>> events = client.fetch_idle()
179 # more complex use for example, with glib/gobject:
180 >>> def callback(source, condition):
181 >>> changes = client.fetch_idle()
183 >>> return False # removes the IO watcher
185 >>> client.send_idle()
186 >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
187 >>> gobject.MainLoop().run()
189 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
191 Fetching binary content (cover art)
192 -----------------------------------
194 Fetching album covers is possible with albumart, here is an example:
196 .. code-block:: python
198 >>> cli = musicpd.MPDClient()
200 >>> track = "Steve Reich/1978-Music for 18 Musicians"
201 >>> aart = cli.albumart(track, 0)
202 >>> received = int(aart.get('binary'))
203 >>> size = int(aart.get('size'))
204 >>> with open('/tmp/cover', 'wb') as cover:
205 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
206 >>> cover.write(aart.get('data'))
207 >>> while received < size:
208 >>> aart = cli.albumart(track, received)
209 >>> cover.write(aart.get('data'))
210 >>> received += int(aart.get('binary'))
211 >>> if received != size:
212 >>> print('something went wrong', file=sys.stderr)
215 A `CommandError` is raised if the album does not expose a cover.
217 You can also use `readpicture` command to fetch embedded picture:
219 .. code-block:: python
221 >>> cli = musicpd.MPDClient()
223 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
224 >>> rpict = cli.readpicture(track, 0)
226 >>> print('No embedded picture found', file=sys.stderr)
228 >>> size = int(rpict['size'])
229 >>> done = int(rpict['binary'])
230 >>> with open('/tmp/cover', 'wb') as cover:
231 >>> cover.write(rpict['data'])
232 >>> while size > done:
233 >>> rpict = cli.readpicture(track, done)
234 >>> done += int(rpict['binary'])
235 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
236 >>> cover.write(rpict['data'])
239 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
247 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
249 A timeout is used for the initial MPD connection (``connect`` command), then
250 the socket is put in blocking mode with no timeout. Its value is set in
251 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
252 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
253 is possible to set socket timeout for all command setting
254 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
256 Having ``socket_timeout`` enabled can help to detect "half-open connection".
257 For instance loosing connectivity without the server explicitly closing the
258 connection (switching network interface ethernet/wifi, router down, etc…).
260 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
261 timeout. A couple of seconds should be enough for commands to complete except
262 for the special case of ``idle`` command which by definition *“ waits until
263 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
264 protocol documentation`_).
266 Here is a solution to use ``idle`` command with ``socket_timeout``:
268 .. code-block:: python
274 cli = musicpd.MPDClient()
276 cli.socket_timeout = 10 # seconds
277 select_timeout = 5 # second
280 cli.send_idle() # use send_ API to avoid blocking on read
281 _read, _, _ = select.select([cli], [], [], select_timeout)
282 if _read: # tries to read response
283 ret = cli.fetch_idle()
284 print(', '.join(ret)) # Do something
287 except socket.timeout as err:
288 print(f'{err} (timeout {cli.socket_timeout})')
289 except (OSError, musicpd.MPDError) as err:
291 if cli._sock is not None:
293 except KeyboardInterrupt:
298 * First launch a non blocking ``idle`` command. This call do not wait for a
299 response to avoid socket timeout waiting for an MPD event.
300 * ``select`` waits for something to read on the socket (the idle response
301 in this case), returns after ``select_timeout`` seconds anyway.
302 * In case there is something to read read it using ``fetch_idle``
303 * Nothing to read, cancel idle with ``noidle``
305 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
306 triggering a socket timeout unless the connection is actually lost (actually it
307 could also be that MPD took too much time to answer, but MPD taking more than a
308 couple of seconds for these commands should never occur).
311 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
312 .. _snake case: https://en.wikipedia.org/wiki/Snake_case
313 .. vim: spell spelllang=en