1 # -*- coding: utf-8 -*-
3 from locale import getpreferredencoding
4 from optparse import (OptionParser, OptionValueError, SUPPRESS_HELP)
8 # pop out 'sw' value before creating OptionParser object.
12 'sw': ['-S', '--hostname'],
15 'help': 'Hostname MPD in running on (default: localhost or MPD_HOST if set)'},
17 'sw': ['-P', '--port'],
20 'help': 'Port MPD in listening on (default: 6600 or MPD_PORT if set)'},
24 USAGE = u"""USAGE: %prog [--help] [options]"""
27 def get_mpd_environ():#{{{
29 Retrieve MPD env. var.
31 con_id = dict({'host': 'localhost',
34 mpd_host_env = environ.get('MPD_HOST')
35 mpd_port = environ.get('MPD_PORT')
38 # mpd_host_env = ['pass', 'host'] because MPD_HOST=pass@host
39 mpd_host_env = mpd_host_env.split('@')
40 mpd_host_env.reverse()
41 if len(mpd_host_env[0]) > 0:
42 con_id.update({'host': mpd_host_env[0]})
43 if len(mpd_host_env) > 1:
44 print 'passwd set in MPD_HOST'
45 passwd = mpd_host_env[1]
47 con_id.update({'port': int(mpd_port)})
48 return (con_id, passwd)#}}}
51 class StartOpt(object):
55 def __init__(self, script_info, child_options):#{{{
57 self.localencoding = 'utf8'
59 self.cli_options = dict({})
60 # TODO: dict ?!!? isn't it a list instead?
61 self.cli_args = dict({})
62 self.info = dict(script_info)
63 # options allows to add new cli options within child objects calling
65 self.options = list(child_options + OPTS)
68 def _get_encoding(self):#{{{
69 """Get local encoding"""
70 self.localencoding = getpreferredencoding()#}}}
72 def _u8_convert(self, string):
73 """Convert CLI input string to UTF8 (mpd standart)"""
74 return unicode(string, self.localencoding).encode('UTF-8')
76 def declare_opts(self):#{{{
78 Declare options in OptionParser object.
80 version = self.info.get('version')
81 prog = self.info.get('prog_name')
82 des = self.info.get('description')
83 if 'usage' in self.info:
84 usage = self.info.get('usage')
87 self.parser = OptionParser(version=version,
91 con_id, passwd = get_mpd_environ()
92 # Add all options declare in OPTS
93 for opt in self.options:
94 opt_names = opt.pop('sw')
95 self.parser.add_option(*opt_names, **opt)
96 #set defaults for host/port according to env var
97 dest = opt.get('dest')
99 self.parser.set_defaults(host=con_id.get('host'))
101 self.parser.set_defaults(port=con_id.get('port'))#}}}
104 """declare options, parse command line"""
107 (self.cli_options, self.cli_args) = self.parser.parse_args()
114 if __name__ == '__main__':
118 # vim: ai ts=4 sw=4 sts=4 expandtab