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 print(client.cmd('foo', 42)) # print result of the request "cmd foo 42"
21 # (nb. for actual command, see link to the protocol below)
22 client.disconnect() # disconnect from the server
24 In the example above `cmd` in not an actual MPD command, for a list of
25 supported commands, their arguments (as MPD currently understands
26 them), and the functions used to parse their responses see :ref:`commands`.
28 See the `MPD protocol documentation`_ for more details.
30 .. _environment_variables:
35 The client honors the following environment variables:
37 * ``MPD_HOST`` MPD host (:abbr:`FQDN (fully qualified domain name)`, socket path or abstract socket) and password.
39 | To define a password set MPD_HOST to "`password@host`" (password only "`password@`")
40 | For abstract socket use "@" as prefix : "`@socket`" and then with a password "`pass@@socket`"
41 | Regular unix socket are set with an absolute path: "`/run/mpd/socket`"
42 * ``MPD_PORT`` MPD port, relevant for TCP socket only, ie with :abbr:`FQDN (fully qualified domain name)` defined host
43 * ``MPD_TIMEOUT`` timeout for connecting to MPD and waiting for MPD’s response in seconds
44 * ``XDG_RUNTIME_DIR`` path to look for potential socket: ``${XDG_RUNTIME_DIR}/mpd/socket``
51 * If ``MPD_HOST`` is not set, then look for a socket in ``${XDG_RUNTIME_DIR}/mpd/socket``
52 * If there is no socket use ``localhost``
53 * If ``MPD_PORT`` is not set, then use ``6600``
54 * If ``MPD_TIMEOUT`` is not set, then uses :py:obj:`musicpd.CONNECTION_TIMEOUT`
60 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
61 transparently called with :ref:`default setting<default_settings>` (use
62 :ref:`environment variables<environment_variables>` to override defaults).
63 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
65 .. code-block:: python
68 os.environ['MPD_HOST'] = 'mpdhost'
69 with MPDClient() as c:
76 Command lists are also supported using `command_list_ok_begin()` and
77 `command_list_end()` :
79 .. code-block:: python
81 client.command_list_ok_begin() # start a command list
82 client.update() # insert the update command into the list
83 client.status() # insert the status command into the list
84 results = client.command_list_end() # results will be a list with the results
89 Some commands (e.g. delete) allow specifying a range in the form `"START:END"` (cf. `MPD protocol documentation`_ for more details).
91 Possible ranges are: `"START:END"`, `"START:"` and `":"` :
93 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`.
95 .. code-block:: python
97 # An intelligent clear
98 # clears played track in the queue, currentsong included
99 pos = client.currentsong().get('pos', 0)
100 # the range object accepts str, no need to convert to int
101 client.delete((0, pos))
102 # missing end interpreted as highest value possible, pay attention still need a tuple.
103 client.delete((pos,)) # purge queue from current to the end
105 A notable case is the `rangeid` command allowing an empty range specified
106 as a single colon as argument (i.e. sending just ":"):
108 .. code-block:: python
110 # sending "rangeid :" to clear the range, play everything
111 client.rangeid(()) # send an empty tuple
113 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
115 Remember the of the tuple is optional, range can still be specified as single string `START:END`. In case of malformed range a CommandError is still raised.
120 Commands may also return iterators instead of lists if `iterate` is set to
123 .. code-block:: python
125 client.iterate = True
126 for song in client.playlistinfo():
129 Idle prefixed commands
130 ----------------------
132 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
133 send a MPD command and then fetch the result later (non-blocking call).
134 This is useful for the idle command:
136 .. code-block:: python
138 >>> client.send_idle()
139 # do something else or use function like select()
140 # http://docs.python.org/howto/sockets.html#non-blocking-sockets
141 # ex. select([client], [], [])
142 >>> events = client.fetch_idle()
144 # more complex use for example, with glib/gobject:
145 >>> def callback(source, condition):
146 >>> changes = client.fetch_idle()
148 >>> return False # removes the IO watcher
150 >>> client.send_idle()
151 >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
152 >>> gobject.MainLoop().run()
154 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
156 Fetching binary content (cover art)
157 -----------------------------------
159 Fetching album covers is possible with albumart, here is an example:
161 .. code-block:: python
163 >>> cli = musicpd.MPDClient()
165 >>> track = "Steve Reich/1978-Music for 18 Musicians"
166 >>> aart = cli.albumart(track, 0)
167 >>> received = int(aart.get('binary'))
168 >>> size = int(aart.get('size'))
169 >>> with open('/tmp/cover', 'wb') as cover:
170 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
171 >>> cover.write(aart.get('data'))
172 >>> while received < size:
173 >>> aart = cli.albumart(track, received)
174 >>> cover.write(aart.get('data'))
175 >>> received += int(aart.get('binary'))
176 >>> if received != size:
177 >>> print('something went wrong', file=sys.stderr)
180 A `CommandError` is raised if the album does not expose a cover.
182 You can also use `readpicture` command to fetch embedded picture:
184 .. code-block:: python
186 >>> cli = musicpd.MPDClient()
188 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
189 >>> rpict = cli.readpicture(track, 0)
191 >>> print('No embedded picture found', file=sys.stderr)
193 >>> size = int(rpict['size'])
194 >>> done = int(rpict['binary'])
195 >>> with open('/tmp/cover', 'wb') as cover:
196 >>> cover.write(rpict['data'])
197 >>> while size > done:
198 >>> rpict = cli.readpicture(track, done)
199 >>> done += int(rpict['binary'])
200 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
201 >>> cover.write(rpict['data'])
204 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
212 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
214 A timeout is used for the initial MPD connection (``connect`` command), then
215 the socket is put in blocking mode with no timeout. Its value is set in
216 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
217 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
218 is possible to set socket timeout for all command setting
219 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
221 Having ``socket_timeout`` enabled can help to detect "half-open connection".
222 For instance loosing connectivity without the server explicitly closing the
223 connection (switching network interface ethernet/wifi, router down, etc…).
225 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
226 timeout. A couple of seconds should be enough for commands to complete except
227 for the special case of ``idle`` command which by definition *“ waits until
228 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
229 protocol documentation`_).
231 Here is a solution to use ``idle`` command with ``socket_timeout``:
233 .. code-block:: python
239 cli = musicpd.MPDClient()
241 cli.socket_timeout = 10 # seconds
242 select_timeout = 5 # second
245 cli.send_idle() # use send_ API to avoid blocking on read
246 _read, _, _ = select.select([cli], [], [], select_timeout)
247 if _read: # tries to read response
248 ret = cli.fetch_idle()
249 print(', '.join(ret)) # Do something
252 except socket.timeout as err:
253 print(f'{err} (timeout {cli.socket_timeout})')
254 except (OSError, musicpd.MPDError) as err:
256 if cli._sock is not None:
258 except KeyboardInterrupt:
263 * First launch a non blocking ``idle`` command. This call do not wait for a
264 response to avoid socket timeout waiting for an MPD event.
265 * ``select`` waits for something to read on the socket (the idle response
266 in this case), returns after ``select_timeout`` seconds anyway.
267 * In case there is something to read read it using ``fetch_idle``
268 * Nothing to read, cancel idle with ``noidle``
270 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
271 triggering a socket timeout unless the connection is actually lost (actually it
272 could also be that MPD took too much time to answer, but MPD taking more than a
273 couple of seconds for these commands should never occur).
276 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
277 .. vim: spell spelllang=en