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.
11 'sw': ['-S', '--hostname'],
14 'help': 'Hostname MPD in running on (default: localhost or MPD_HOST if set)'},
16 'sw': ['-P', '--port'],
19 'help': 'Port MPD in listening on (default: 6600 or MPD_PORT if set)'},
22 USAGE = u"""USAGE: %prog [--help] [options]"""
25 def get_mpd_environ():
27 Retrieve MPD env. var.
29 con_id = dict({'host': 'localhost',
32 mpd_host_env = environ.get('MPD_HOST')
33 mpd_port = environ.get('MPD_PORT')
36 # mpd_host_env = ['pass', 'host'] because MPD_HOST=pass@host
37 mpd_host_env = mpd_host_env.split('@')
38 mpd_host_env.reverse()
39 if len(mpd_host_env[0]) > 0:
40 con_id.update({'host': mpd_host_env[0]})
41 if len(mpd_host_env) > 1:
42 print 'passwd set in MPD_HOST'
43 passwd = mpd_host_env[1]
44 con_id.update({'passwd': passwd})
46 con_id.update({'port': int(mpd_port)})
47 return (con_id, passwd)
50 class StartOpt(object):
54 def __init__(self, script_info, child_options):
56 self.localencoding = 'utf8'
58 self.cli_options = dict({})
59 # TODO: dict ?!!? isn't it a list instead?
60 self.cli_args = dict({})
61 self.info = dict(script_info)
62 # options allows to add new cli options within child objects calling
64 self.options = list(child_options + OPTS)
67 def _get_encoding(self):
68 """Get local encoding"""
69 self.localencoding = getpreferredencoding()
71 def _u8_convert(self, string):
72 """Convert CLI input string to UTF8 (mpd standart)"""
73 return unicode(string, self.localencoding).encode('UTF-8')
75 def declare_opts(self):
77 Declare options in OptionParser object.
79 version = self.info.get('version')
80 prog = self.info.get('prog_name')
81 des = self.info.get('description')
82 if 'usage' in self.info:
83 usage = self.info.get('usage')
86 self.parser = OptionParser(version=version,
90 con_id, passwd = get_mpd_environ()
91 # Add all options declare in OPTS
92 for opt in self.options:
93 opt_names = opt.pop('sw')
94 self.parser.add_option(*opt_names, **opt)
95 #set defaults for host/port according to env var
96 dest = opt.get('dest')
98 self.parser.set_defaults(host=con_id.get('host'))
100 self.parser.set_defaults(port=con_id.get('port'))
103 """declare options, parse command line"""
106 (self.cli_options, self.cli_args) = self.parser.parse_args()
113 if __name__ == '__main__':
117 # vim: ai ts=4 sw=4 sts=4 expandtab