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 (non-blocking call).
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 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
148 Fetching binary content (cover art)
149 -----------------------------------
151 Fetching album covers is possible with albumart, here is an example:
153 .. code-block:: python
155 >>> cli = musicpd.MPDClient()
157 >>> track = "Steve Reich/1978-Music for 18 Musicians"
158 >>> aart = cli.albumart(track, 0)
159 >>> received = int(aart.get('binary'))
160 >>> size = int(aart.get('size'))
161 >>> with open('/tmp/cover', 'wb') as cover:
162 >>> # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
163 >>> cover.write(aart.get('data'))
164 >>> while received < size:
165 >>> aart = cli.albumart(track, received)
166 >>> cover.write(aart.get('data'))
167 >>> received += int(aart.get('binary'))
168 >>> if received != size:
169 >>> print('something went wrong', file=sys.stderr)
172 A `CommandError` is raised if the album does not expose a cover.
174 You can also use `readpicture` command to fetch embedded picture:
176 .. code-block:: python
178 >>> cli = musicpd.MPDClient()
180 >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
181 >>> rpict = cli.readpicture(track, 0)
183 >>> print('No embedded picture found', file=sys.stderr)
185 >>> size = int(rpict['size'])
186 >>> done = int(rpict['binary'])
187 >>> with open('/tmp/cover', 'wb') as cover:
188 >>> cover.write(rpict['data'])
189 >>> while size > done:
190 >>> rpict = cli.readpicture(track, done)
191 >>> done += int(rpict['binary'])
192 >>> print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
193 >>> cover.write(rpict['data'])
196 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
204 When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
206 A timeout is used for the initial MPD connection (``connect`` command), then
207 the socket is put in blocking mode with no timeout. Its value is set in
208 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
209 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
210 is possible to set socket timeout for all command setting
211 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
213 Having ``socket_timeout`` enabled can help to detect "half-open connection".
214 For instance loosing connectivity without the server explicitly closing the
215 connection (switching network interface ethernet/wifi, router down, etc…).
217 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
218 timeout. A couple of seconds should be enough for commands to complete except
219 for the special case of ``idle`` command which by definition *“ waits until
220 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
221 protocol documentation`_).
223 Here is a solution to use ``idle`` command with ``socket_timeout``:
225 .. code-block:: python
231 cli = musicpd.MPDClient()
233 cli.socket_timeout = 10 # seconds
234 select_timeout = 5 # second
237 cli.send_idle() # use send_ API to avoid blocking on read
238 _read, _, _ = select.select([cli], [], [], select_timeout)
239 if _read: # tries to read response
240 ret = cli.fetch_idle()
241 print(', '.join(ret)) # Do something
244 except socket.timeout as err:
245 print(f'{err} (timeout {cli.socket_timeout})')
246 except (OSError, musicpd.MPDError) as err:
248 if cli._sock is not None:
250 except KeyboardInterrupt:
255 * First launch a non blocking ``idle`` command. This call do not wait for a
256 response to avoid socket timeout waiting for an MPD event.
257 * ``select`` waits for something to read on the socket (the idle response
258 in this case), returns after ``select_timeout`` seconds anyway.
259 * In case there is something to read read it using ``fetch_idle``
260 * Nothing to read, cancel idle with ``noidle``
262 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
263 triggering a socket timeout unless the connection is actually lost (actually it
264 could also be that MPD took too much time to answer, but MPD taking more than a
265 couple of seconds for these commands should never occur).
268 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
269 .. vim: spell spelllang=en