]> kaliko git repositories - python-musicpd.git/blob - doc/source/examples/exceptions.py
Releasing 0.9.0
[python-musicpd.git] / doc / source / examples / exceptions.py
1 """client class dealing with all Exceptions
2 """
3 import logging
4
5 import musicpd
6
7
8 # Wrap Exception decorator
9 def wrapext(func):
10     """Decorator to wrap errors in musicpd.MPDError"""
11     errors=(OSError, TimeoutError)
12     into = musicpd.MPDError
13     def w_func(*args, **kwargs):
14         try:
15             return func(*args, **kwargs)
16         except errors as err:
17             strerr = str(err)
18             if hasattr(err, 'strerror'):
19                 if err.strerror:
20                     strerr = err.strerror
21             raise into(strerr) from err
22     return w_func
23
24
25 class MyClient(musicpd.MPDClient):
26     """Plain client inheriting from MPDClient"""
27
28     def __init__(self):
29         # Set logging to debug level
30         logging.basicConfig(level=logging.DEBUG,
31                 format='%(levelname)-8s %(module)-10s %(message)s')
32         self.log = logging.getLogger(__name__)
33         super().__init__()
34
35     @wrapext
36     def __getattr__(self, cmd):
37         """Wrapper around MPDClient calls for abstract overriding"""
38         self.log.debug('cmd: %s', cmd)
39         return super().__getattr__(cmd)
40
41
42 if __name__ == '__main__':
43     cli = MyClient()
44     # You can overrides host here or in init
45     #cli.host = 'example.org'
46     # Connect MPD server
47     try:
48         cli.connect()
49         cli.currentsong()
50         cli.stats()
51     except musicpd.MPDError as error:
52         cli.log.fatal(error)
53     finally:
54         cli.log.info('Disconnecting')
55         try:
56             # Tries to close the socket anyway
57             cli.disconnect()
58         except OSError:
59             pass