Make harmless changes to reduce pylint noise.

Work out what to do about warnings and apparent errors later.
This commit is contained in:
Ferdi Franceschini
2014-07-05 22:32:34 +10:00
parent a0465541b3
commit 37e75ab5b4

View File

@@ -1,9 +1,11 @@
#!/usr/bin/env python
"""Provides a sics_config.ini file viewer and editor.
"""
# vim: tabstop=8 softtabstop=4 shiftwidth=4 nocin si et ft=python
# View Screen has 3 parts
# (Instrument Configuration), (Configuration Options), (Option Implementation)
# Uses MVC implemented as InstConfigData<M>, InstConfigView<V>, InstConfigManager<C>
# Uses MVC as InstConfigData<M>, InstConfigView<V>, InstConfigManager<C>
#
# InstConfigData <>--- ConfigParser.SafeConfig
# |--set_cfparse()
@@ -26,10 +28,9 @@ import shutil
import argparse
import ConfigParser
import urwid
import copy
from collections import defaultdict
Palette = [
PALETTE = [
('body', 'dark cyan', '', 'standout'),
('focus', 'dark red', '', 'standout'),
('head', 'light red', 'black'),
@@ -37,12 +38,26 @@ Palette = [
class RadioButtonListWalker(urwid.SimpleListWalker):
"""Extend urwid.SimpleListWalker to generate a radio button listwalker.
Attributes:
button_dict (dict): Maps radiobutton labels to an urwid.RadioButton.
"""
def __init__(self, item_states, on_state_change=None, user_data=None):
"""
Args:
item_states (list of tuples): [(button name, state)].
on_state_change: 'change' signal handler for each radiobutton.
user_data: data passed to signal handler.
"""
radio_grp = []
mapped_rb_list = []
self.button_dict = {}
for item,stateval in item_states:
rb = urwid.RadioButton(radio_grp, item, state=stateval, on_state_change=on_state_change, user_data=user_data)
for item, stateval in item_states:
rb = urwid.RadioButton( radio_grp, item, state=stateval,
on_state_change=on_state_change, user_data=user_data )
self.button_dict[item] = rb
mapped_rb = urwid.AttrMap(rb, 'body', 'focus')
mapped_rb_list.append(mapped_rb)
@@ -52,11 +67,25 @@ class RadioButtonListWalker(urwid.SimpleListWalker):
class CheckBoxListWalker(urwid.SimpleListWalker):
"""Extend urwid.SimpleListWalker to generate a checkbox listwalker.
Attributes:
button_dict (dict): Maps checkbox labels to an urwid.CheckBox.
"""
def __init__(self, item_states, on_state_change = None, user_data = None):
"""
Args:
item_states (list of tuples): [(button name, state)].
on_state_change: 'change' signal handler for each radiobutton.
user_data: data passed to signal handler.
"""
mapped_cb_list = []
self.button_dict = {}
for item,stateval in item_states:
cb = urwid.CheckBox(item, state = stateval, on_state_change = on_state_change, user_data = user_data)
for item, stateval in item_states:
cb = urwid.CheckBox( item, state = stateval,
on_state_change = on_state_change,
user_data = user_data )
self.button_dict[item] = cb
mapped_cb = urwid.AttrMap(cb, 'body', 'focus')
mapped_cb_list.append(mapped_cb)
@@ -66,16 +95,29 @@ class CheckBoxListWalker(urwid.SimpleListWalker):
class OptionListWalker(CheckBoxListWalker):
"""Extend CheckBoxListWalker to generate a listwalker from an
InstConfigData option description.
"""
def __init__(self, opt_dict, statechange_cb):
"""
Args:
opt_dict: InstConfigData option description dictionary.
statechange_cb: 'change' signal handler for each checkbox.
"""
urwid.register_signal(OptionListWalker, ['focus_change'])
item_states = [(i,d['enabled']) for i,d in opt_dict.iteritems()]
item_states = [(i, d['enabled']) for i, d in opt_dict.iteritems()]
item_states.sort()
super(OptionListWalker, self).__init__(item_states, statechange_cb)
return
def set_focus(self, pos):
dbg.msg(0, 'OptionListWalker:set_focus({0}) -> emit focus_change'.format(pos))
"""Emit 'focus_change' signal with position of button.
"""
DBG.msg(0,
'OptionListWalker:set_focus({0})->emit focus_change'.format(pos))
urwid.emit_signal(self, 'focus_change', pos)
return super(OptionListWalker, self).set_focus(pos)
@@ -84,8 +126,12 @@ class OptionListWalker(CheckBoxListWalker):
# list using the 'up' or 'down' keys
class ClosedListBox(urwid.ListBox):
"""Extend urwid.ListBox to prevent navigating outside of the listbox.
"""
def keypress(self, size, key):
"""Prevents navigating outside of a ClosedListBox with the up and down arrow keys"""
"""Override keypress to limit navigation to within listbox.
"""
pos = self.get_focus()[1]
ll = len(self.body)
if (pos <= 0 and key == 'up') or (pos >= ll-1 and key == 'down'):
@@ -96,6 +142,11 @@ class ClosedListBox(urwid.ListBox):
# List of Checkboxes
class OptionListBox(ClosedListBox):
"""Extend ClosedListBox doesn't add anything but it may come in handy
someday when defining behaviour of configuration option lists.
"""
def __init__(self, listwalker):
super(OptionListBox, self).__init__(listwalker)
return
@@ -103,46 +154,67 @@ class OptionListBox(ClosedListBox):
# List of RadioButtons
class ImpListBox(ClosedListBox):
"""Extend ClosedListBox to allow updating implementation lists when
selecting a configuration option.
"""
def __init__(self, listwalker):
super(ImpListBox, self).__init__(listwalker)
return
def use_listwalker(self, liswalker):
self.body.contents[:] = liswalker
def use_listwalker(self, listwalker):
""" Select the given listwalker for display.
"""
self.body.contents[:] = listwalker
return
class InstConfigData:
"""Handles reading and writing instrument configuration data and provides
methods to change the configuration.
Attributes:
configuration_dict: Instrument configurations by configuration name.
opt_dict: Configuration option descriptions indexed by option name.
imp_dict: Implementations for indexed by option type.
"""
msg_index = 4
# configuration_dict: dict of instrument configurations as defined below,
# {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} }
configuration_dict = defaultdict(dict)
# imp_dict: dict of implementations indexed by optype,
# {optype: [impname] }
imp_dict = defaultdict(list)
def __init__(self):
#configuration_dict: dict of instrument configurations as defined below,
# {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} }
self.configuration_dict = defaultdict(dict)
# opt_dict: dict of configuration options as defined below,
# {optname:{'enabled': T/F/Always, 'imptype':optype, 'selected_imp':dflt}}
opt_dict = defaultdict(dict)
#imp_dict: dict of implementations indexed by optype,
# {optype: [impname] }
self.imp_dict = defaultdict(list)
# imp2opt_dict: Maps each implementation to an option or None,
# {imp: opt/None}
imp2opt_dict = {}
#opt_dict: dict of configuration options as defined below,
# {optname:{'enabled':T/F/Always, 'imptype':optype,'selected_imp':dflt}}
self.opt_dict = defaultdict(dict)
# optypelist: list of (opt, optype) tuples
# [(opt, optype)]
optypelist = []
#imp2opt_dict: Maps each implementation to an option or None,
# {imp: opt/None}
self.imp2opt_dict = {}
#optypelist: list of (opt, optype) tuples
# [(opt, optype)]
self.optypelist = []
def __get_configurations(self):
"""Parse instrument configuration definitions from INI file into
configuration_dict attribute of InstConfigData object
"""
for s in self.file_parser.sections():
cascade_list = []
if self.file_parser.has_option(s, 'cascade'):
enabled = self.file_parser.get(s, 'enabled')
for cascade_str in self.file_parser.get(s,'cascade').split(','):
for cascade_str in self.file_parser.get(s,
'cascade').split(','):
cascade_list.append(tuple(cascade_str.split(':')))
if enabled.lower() in ['true','always']:
if enabled.lower() in ['true', 'always']:
stateval = True
else:
stateval = False
@@ -151,6 +223,9 @@ class InstConfigData:
self.configuration_dict[s]['cascade_list'] = cascade_list
def __get_options(self):
"""Parse configuration options from INI file into opt_dict attribute of
InstConfigData object.
"""
for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'implementation'):
selected_imp = self.file_parser.get(s, 'implementation')
@@ -178,10 +253,14 @@ class InstConfigData:
else:
self.opt_dict[s]['selected_imp'] = selected_imp
if selected_imp != 'none':
print 'Add imp2opt_dict[{0}] = {1}'.format(selected_imp,s)
print 'Add imp2opt_dict[{0}]={1}'.format(
selected_imp, s)
self.imp2opt_dict[selected_imp] = s
def __get_implementations(self):
"""Parse implementation lists from INI file into imp_dict attribute of
InstConfigData object.
"""
for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'imptype'):
key = self.file_parser.get(s, 'imptype')
@@ -194,16 +273,18 @@ class InstConfigData:
self.imp2opt_dict[s] = 'none'
def read_config_file(self, config_filename):
""" Load and parse a sics_config.ini file """
self.config_filename = config_filename
self.file_parser = ConfigParser.SafeConfigParser()
self.file_parser.read(config_filename)
self.__get_options()
self.__get_implementations()
self.__get_configurations()
for opt,dict in self.opt_dict.iteritems():
for opt, dict in self.opt_dict.iteritems():
self.optypelist.append((opt, dict['imptype']))
def backup_files(self):
""" Backup configuration files """
for idx in range(8, 0, -1):
if os.path.exists(self.config_filename + "." + str(idx)):
os.rename(self.config_filename + "." + str(idx),
@@ -213,7 +294,8 @@ class InstConfigData:
shutil.copy(self.config_filename, self.config_filename + ".1")
def write_config_file(self):
for item,dict in self.opt_dict.iteritems():
""" Write out InstConfigData values to the configuration file."""
for item, dict in self.opt_dict.iteritems():
if 'permanent' in dict and dict['permanent'] == True:
enabled = 'Always'
else:
@@ -223,45 +305,58 @@ class InstConfigData:
self.file_parser.set(item, 'implementation', dict['selected_imp'])
self.file_parser.set(item, 'optype', dict['imptype'])
for item,dict in self.configuration_dict.iteritems():
for item, dict in self.configuration_dict.iteritems():
enabled = dict['enabled'].__str__()
self.file_parser.set(item, 'enabled', enabled)
for imp,opt in self.imp2opt_dict.iteritems():
for imp, opt in self.imp2opt_dict.iteritems():
if imp != 'none' and opt != 'none' and 'id' in self.opt_dict[opt]:
self.file_parser.set(imp, 'id', self.opt_dict[opt]['id'])
with open(self.config_filename,'w') as cfile:
with open(self.config_filename, 'w') as cfile:
for section in sorted(self.file_parser.sections()):
cfile.write("[%s]\n" % section)
for option in sorted(self.file_parser.options(section)):
cfile.write("%s = %s\n" % (option, self.file_parser.get(section, option)))
cfile.write(
'{0} = {1}\n'.format(option,
self.file_parser.get(section,
option)))
cfile.write("\n")
def set_imp(self, opt, new_imp):
old_imp =self.opt_dict[opt]['selected_imp']
"""Keep option dictionaray and implementation -> option map in sync."""
old_imp = self.opt_dict[opt]['selected_imp']
self.imp2opt_dict[old_imp] = 'none'
self.opt_dict[opt]['selected_imp'] = new_imp
self.imp2opt_dict[new_imp] = opt
def get_optypelist (self):
"""Return a list of (option, optype) tuples."""
return self.optypelist
def iter_implementations(self, opt):
"""Iterate over implementation names for the given option."""
dict = self.opt_dict[opt]
for imp in self.imp_dict[dict['imptype']]:
yield imp
def cf_statechange(self, cfg_id, new_state, udat=None):
"""Change the given instrument configuration state."""
self.configuration_dict[cfg_id]['enabled'] = new_state
def opt_statechange(self, opt, new_state, udat=None):
dbg.msg(3, 'InstConfigData:opt_statechange({0},{1},{2})'.format(opt, new_state, udat))
"""Change the given option state."""
DBG.msg(3,
'InstConfigData:opt_statechange({0},{1},{2})'.format(opt,
new_state, udat))
self.opt_dict[opt]['enabled'] = new_state
def imp_statechange(self, selected_imp, new_state, opt):
dbg.msg(self.msg_index, 'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp, new_state, opt))
"""Change the given implementation state."""
DBG.msg(self.msg_index,
'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp,
new_state, opt))
self.msg_index = (self.msg_index - 3) % 2 + 4
if new_state == True:
self.opt_dict[opt]['selected_imp'] = selected_imp
@@ -269,7 +364,15 @@ class InstConfigData:
class InstConfigView(urwid.Pile):
"""Extend urwid.Pile to provide an instrument configuration viewer.
"""
def __init__(self, cf_dat, cf_man, dbmsg):
"""
Args:
cf_dat: InstConfigData object.
cf_man: InstConfigManager object.
"""
self.cf_dat = cf_dat
self.cf_man = cf_man
option_ListBoxes = [
@@ -282,6 +385,7 @@ class InstConfigView(urwid.Pile):
return
def keyinput(self, key):
"""Switch between lists, save data and quit on key input."""
if key == 'meta q':
raise urwid.ExitMainLoop()
elif key == 'w':
@@ -309,8 +413,11 @@ class InstConfigView(urwid.Pile):
# Tracks selected implementation for each option
# and sets selection on ImpListBox
class InstConfigManager:
"""Provides controller which keeps data and viewer in sync.
"""
cf_msg_index = 8
imp_lw_dict = {}
def __init__(self, cf_dat):
self.cf_dat = cf_dat
urwid.register_signal(InstConfigManager, ['focus_change'])
@@ -321,19 +428,25 @@ class InstConfigManager:
self.imp_lw = self.__gen_imp_listwalker(firstopt)
self.opt_lw = OptionListWalker(cf_dat.opt_dict, self.opt_statechange)
for label, button in self.opt_lw.button_dict.iteritems():
button.set_label('{0}:{1}'.format(label, self.cf_dat.opt_dict[label]['selected_imp']))
button.set_label('{0}:{1}'.format(
label, self.cf_dat.opt_dict[label]['selected_imp']) )
self.imp_lb = ImpListBox(self.imp_lw)
urwid.connect_signal(self.opt_lw, 'focus_change', self.update_imp_lb)
item_states = [(i,d['enabled']) for i,d in cf_dat.configuration_dict.iteritems()]
item_states = [(i, d['enabled']) for i, d in
cf_dat.configuration_dict.iteritems()]
item_states.sort()
self.cfg_lw = RadioButtonListWalker(item_states, on_state_change = self.cf_statechange)
self.cfg_lw = RadioButtonListWalker(item_states, on_state_change =
self.cf_statechange)
self.config_lb = OptionListBox(self.cfg_lw)
self.opt_lb = OptionListBox(self.opt_lw)
self.opt_lb.set_focus(0)
return
def __imp_unavailable(self, imp):
"""Return True if an implementation is unavailable because it is used
by an enabled option.
"""
if imp == 'none':
return False
@@ -346,6 +459,7 @@ class InstConfigManager:
return False
def __gen_imp_listwalker(self, opt):
"""Generate the appropriate listwalker for the given option."""
imp_items = []
for imp in self.cf_dat.iter_implementations(opt):
if self.__imp_unavailable(imp):
@@ -357,10 +471,15 @@ class InstConfigManager:
imp_items = imp_items[:1] + sorted(imp_items[1:])
rb_lw = RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt)
rb_lw = RadioButtonListWalker(imp_items,
on_state_change=self.imp_statechange,
user_data=opt)
return rb_lw
def cf_statechange(self, button, new_state, udat=None):
"""Update option list when an instrument configuration is selected and
notify InstConfigData object.
"""
cfg_id = button.get_label()
self.cf_dat.cf_statechange(cfg_id, new_state, udat)
cascade = self.cf_dat.configuration_dict[cfg_id]['cascade_list']
@@ -368,7 +487,7 @@ class InstConfigManager:
for opt in self.cf_dat.opt_dict.keys():
self.opt_lw.button_dict[opt].set_state(False)
for opt,imp in cascade:
for opt, imp in cascade:
self.cf_dat.set_imp(opt, imp)
self.opt_lw.button_dict[opt].set_state(True)
imp_lw = self.__gen_imp_listwalker(opt)
@@ -377,11 +496,16 @@ class InstConfigManager:
if self.cf_dat.opt_dict[opt]['permanent'] == True:
self.opt_lw.button_dict[opt].set_state(True)
dbg.msg(self.cf_msg_index, 'InstConfigManager:cf_statechange({0},{1},{2}), cascade = {3}'.format(cfg_id, new_state, udat, cascade))
DBG.msg(self.cf_msg_index,
'InstConfigManager:cf_statechange({0},{1},{2}),cascade={3}'.format(
cfg_id, new_state, udat, cascade))
self.cf_msg_index = (self.cf_msg_index - 7) % 2 + 8
return
def opt_statechange(self, button, new_state, udat=None):
"""Update option label when it changes state and notify InstConfigData
object.
"""
opt = button.get_label().split(':')[0]
imp = self.cf_dat.opt_dict[opt]['selected_imp']
if new_state == True:
@@ -393,12 +517,15 @@ class InstConfigManager:
opt_button.set_label('{0}:none'.format(opt))
else:
opt_button = self.opt_lw.button_dict[opt]
opt_button.set_label('{0}:{1}'.format(opt,imp))
opt_button.set_label('{0}:{1}'.format(opt, imp))
self.cf_dat.set_imp(opt, imp)
self.cf_dat.opt_statechange(opt, new_state, udat)
def imp_statechange(self, button, new_state, opt):
"""Update label on the configuration option when it's implementation is
changed.
"""
if new_state == True:
imp = button.get_label()
self.cf_dat.set_imp(opt, imp)
@@ -409,17 +536,19 @@ class InstConfigManager:
return
def update_imp_lb(self, pos):
"""Update implementation list when an option gets focus."""
optname = self.opt_optype_list[pos][0]
optype = self.opt_optype_list[pos][1]
mstr = 'InstConfigManager:update_imp_lb({0}) -> select {1}'.format(pos, optype)
dbg.msg(1, mstr)
mstr = 'InstConfigManager:update_imp_lb({0})->select{1}'.format(pos,
optype)
DBG.msg(1, mstr)
self.imp_lw = self.__gen_imp_listwalker(optname)
self.imp_lb.use_listwalker(self.imp_lw)
return
import pdb
class DEBUG:
"""DEBUG class"""
msgTextDict = {}
msglist = []
msg_ids = [ 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9' ]
@@ -435,13 +564,14 @@ class DEBUG:
self.mlb = urwid.ListBox(mlw)
def msg(self, index, msg):
"""Debug message."""
if self.enabled:
mid = self.msg_ids[index]
self.msgTextDict[mid].set_text(msg)
dbg = DEBUG(enabled=True)
DBG = DEBUG(enabled=True)
def main(config_ini):
global cf_dat, cf_man, cf_viewer
"""Create configuration editor."""
# Make configuration data
cf_dat = InstConfigData()
@@ -451,22 +581,26 @@ def main(config_ini):
cf_man = InstConfigManager(cf_dat)
# Make configuration viewer
cf_viewer = InstConfigView(cf_dat, cf_man, dbg.mlb)
urwid.MainLoop(cf_viewer, Palette, unhandled_input=cf_viewer.keyinput).run()
cf_viewer = InstConfigView(cf_dat, cf_man, DBG.mlb)
urwid.MainLoop(cf_viewer, PALETTE, unhandled_input=cf_viewer.keyinput).run()
return
if '__main__' == __name__:
default_ini = "/usr/local/sics/sics_config.ini"
parser = argparse.ArgumentParser(description = """
DEFAULT_INI = "/usr/local/sics/sics_config.ini"
PARSER = argparse.ArgumentParser(description = """
Edit a configuration (*.ini) file using python urwid widget library.
Options can be enabled or disabled with mouse or spacebar.
Navigate with arrow keys.
Press W to save.
Press Alt-Q to quit.
The default configuration filename is %s.
""" % default_ini)
parser.add_argument("-v", "--verbose", action="store_true", help="give more info in the footer")
parser.add_argument("path", nargs="?", default = default_ini, help="name of file to edit [%s]" % default_ini)
args = parser.parse_args()
default_ini = os.path.abspath(args.path)
main(default_ini)
""" % DEFAULT_INI)
PARSER.add_argument(
"-v", "--verbose", action="store_true",
help="give more info in the footer")
PARSER.add_argument(
"path", nargs="?", default = DEFAULT_INI,
help="name of file to edit [%s]" % DEFAULT_INI)
ARGS = PARSER.parse_args()
DEFAULT_INI = os.path.abspath(ARGS.path)
main(DEFAULT_INI)