1 .. SPDX-FileCopyrightText: 2018-2021 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 Provide a 2-tuple as argument for command supporting ranges (cf. `MPD protocol documentation`_ for more details).
90 Possible ranges are: "START:END", "START:" and ":" :
92 .. code-block:: python
94 # An intelligent clear
95 # clears played track in the queue, currentsong included
96 pos = client.currentsong().get('pos', 0)
97 # the 2-tuple range object accepts str, no need to convert to int
98 client.delete((0, pos))
99 # missing end interpreted as highest value possible, pay attention still need a tuple.
100 client.delete((pos,)) # purge queue from current to the end
102 A notable case is the `rangeid` command allowing an empty range specified
103 as a single colon as argument (i.e. sending just ":"):
105 .. code-block:: python
107 # sending "rangeid :" to clear the range, play everything
108 client.rangeid(()) # send an empty tuple
110 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
115 Commands may also return iterators instead of lists if `iterate` is set to
118 .. code-block:: python
120 client.iterate = True
121 for song in client.playlistinfo():
124 Idle prefixed commands
125 ----------------------
127 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
128 send a MPD command and then fetch the result later (non-blocking call).
129 This is useful for the idle command:
131 .. code-block:: python
133 >>> client.send_idle()
134 # do something else or use function like select()
135 # http://docs.python.org/howto/sockets.html#non-blocking-sockets
136 # ex. select([client], [], [])
137 >>> events = client.fetch_idle()
139 # more complex use for example, with glib/gobject:
140 >>> def callback(source, condition):
141 >>> changes = client.fetch_idle()
143 >>> return False # removes the IO watcher
145 >>> client.send_idle()
146 >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
147 >>> gobject.MainLoop().run()
149 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
151 Fetching binary content (cover art)
152 -----------------------------------
154 Fetching album covers is possible with albumart, here is an example:
156 .. code-block:: python
158 >>> cli = musicpd.MPDClient()
160 >>> track = "Steve Reich/1978-Music for 18 Musicians"
161 >>> aart = cli.albumart(track, 0)
162 >>> received = int(aart.get('binary'))
163 >>> size = int(aart.get('size'))
164 >>> with open('/tmp/cover', 'wb') as cover:
165 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
166 >>> cover.write(aart.get('data'))
167 >>> while received < size:
168 >>> aart = cli.albumart(track, received)
169 >>> cover.write(aart.get('data'))
170 >>> received += int(aart.get('binary'))
171 >>> if received != size:
172 >>> print('something went wrong', file=sys.stderr)
175 A `CommandError` is raised if the album does not expose a cover.
177 You can also use `readpicture` command to fetch embedded picture:
179 .. code-block:: python
181 >>> cli = musicpd.MPDClient()
183 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
184 >>> rpict = cli.readpicture(track, 0)
186 >>> print('No embedded picture found', file=sys.stderr)
188 >>> size = int(rpict['size'])
189 >>> done = int(rpict['binary'])
190 >>> with open('/tmp/cover', 'wb') as cover:
191 >>> cover.write(rpict['data'])
192 >>> while size > done:
193 >>> rpict = cli.readpicture(track, done)
194 >>> done += int(rpict['binary'])
195 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
196 >>> cover.write(rpict['data'])
199 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
207 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
209 A timeout is used for the initial MPD connection (``connect`` command), then
210 the socket is put in blocking mode with no timeout. Its value is set in
211 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
212 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
213 is possible to set socket timeout for all command setting
214 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
216 Having ``socket_timeout`` enabled can help to detect "half-open connection".
217 For instance loosing connectivity without the server explicitly closing the
218 connection (switching network interface ethernet/wifi, router down, etc…).
220 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
221 timeout. A couple of seconds should be enough for commands to complete except
222 for the special case of ``idle`` command which by definition *“ waits until
223 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
224 protocol documentation`_).
226 Here is a solution to use ``idle`` command with ``socket_timeout``:
228 .. code-block:: python
234 cli = musicpd.MPDClient()
236 cli.socket_timeout = 10 # seconds
237 select_timeout = 5 # second
240 cli.send_idle() # use send_ API to avoid blocking on read
241 _read, _, _ = select.select([cli], [], [], select_timeout)
242 if _read: # tries to read response
243 ret = cli.fetch_idle()
244 print(', '.join(ret)) # Do something
247 except socket.timeout as err:
248 print(f'{err} (timeout {cli.socket_timeout})')
249 except (OSError, musicpd.MPDError) as err:
251 if cli._sock is not None:
253 except KeyboardInterrupt:
258 * First launch a non blocking ``idle`` command. This call do not wait for a
259 response to avoid socket timeout waiting for an MPD event.
260 * ``select`` waits for something to read on the socket (the idle response
261 in this case), returns after ``select_timeout`` seconds anyway.
262 * In case there is something to read read it using ``fetch_idle``
263 * Nothing to read, cancel idle with ``noidle``
265 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
266 triggering a socket timeout unless the connection is actually lost (actually it
267 could also be that MPD took too much time to answer, but MPD taking more than a
268 couple of seconds for these commands should never occur).
271 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
272 .. vim: spell spelllang=en