From b5a4d70ab816489505dcf28ced48531ce7b0beef Mon Sep 17 00:00:00 2001 From: David Paleino Date: Sat, 17 Nov 2012 01:07:08 +0100 Subject: [PATCH] Fix some issues by pylint --- cli/wicd-cli.py | 113 ++++++----- curses/configscript_curses.py | 90 +++++---- curses/curses_misc.py | 341 ++++++++++++++++++---------------- in/wicd=wpath.py.in | 8 +- wicd/__init__.py | 1 + wicd/autoconnect.py | 12 +- wicd/backend.py | 6 +- wicd/backends/__init__.py | 1 + wicd/backends/be-ioctl.py | 14 +- wicd/configmanager.py | 22 ++- wicd/dbusmanager.py | 19 +- wicd/logfile.py | 17 +- wicd/misc.py | 30 ++- wicd/monitor.py | 26 ++- wicd/networking.py | 81 ++++++-- wicd/suspend.py | 10 +- wicd/translations.py | 17 +- wicd/wicd-daemon.py | 194 +++++++++++-------- wicd/wnettools.py | 175 +++++++++++------ 19 files changed, 729 insertions(+), 448 deletions(-) diff --git a/cli/wicd-cli.py b/cli/wicd-cli.py index 0a69a3c..47cdc3e 100755 --- a/cli/wicd-cli.py +++ b/cli/wicd-cli.py @@ -1,5 +1,6 @@ #!/usr/bin/python +""" Scriptable command-line interface. """ # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or @@ -32,20 +33,30 @@ else: bus = dbus.SystemBus() try: - daemon = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon'), - 'org.wicd.daemon') - wireless = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wireless'), - 'org.wicd.daemon.wireless') - wired = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wired'), - 'org.wicd.daemon.wired') - config = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/config'), - 'org.wicd.daemon.config') + daemon = dbus.Interface( + bus.get_object('org.wicd.daemon', '/org/wicd/daemon'), + 'org.wicd.daemon' + ) + wireless = dbus.Interface( + bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wireless'), + 'org.wicd.daemon.wireless' + ) + wired = dbus.Interface( + bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wired'), + 'org.wicd.daemon.wired' + ) + config = dbus.Interface( + bus.get_object('org.wicd.daemon', '/org/wicd/daemon/config'), + 'org.wicd.daemon.config' + ) except dbus.DBusException: - print 'Error: Could not connect to the daemon. Please make sure it is running.' + print 'Error: Could not connect to the daemon. ' + \ + 'Please make sure it is running.' sys.exit(3) if not daemon: - print 'Error connecting to wicd via D-Bus. Please make sure the wicd service is running.' + print 'Error connecting to wicd via D-Bus. ' + \ + 'Please make sure the wicd service is running.' sys.exit(3) parser = optparse.OptionParser() @@ -61,12 +72,14 @@ parser.add_option('--list-networks', '-l', default=False, action='store_true') parser.add_option('--network-details', '-d', default=False, action='store_true') parser.add_option('--disconnect', '-x', default=False, action='store_true') parser.add_option('--connect', '-c', default=False, action='store_true') -parser.add_option('--list-encryption-types', '-e', default=False, action='store_true') +parser.add_option('--list-encryption-types', '-e', default=False, + action='store_true') # short options for these aren't great. parser.add_option('--wireless', '-y', default=False, action='store_true') parser.add_option('--wired', '-z', default=False, action='store_true') parser.add_option('--load-profile', '-o', default=False, action='store_true') -parser.add_option('--status', '-i', default=False, action='store_true') # -i(nfo) +parser.add_option('--status', '-i', default=False, + action='store_true') # -i(nfo) options, arguments = parser.parse_args() @@ -114,12 +127,14 @@ if options.status: # functions def is_valid_wireless_network_id(network_id): + """ Check if it's a valid wireless network. '""" if not (network_id >= 0 \ and network_id < wireless.GetNumberOfNetworks()): print 'Invalid wireless network identifier.' sys.exit(1) def is_valid_wired_network_id(network_id): + """ Check if it's a valid wired network. '""" num = len(wired.GetWiredProfileList()) if not (network_id < num and \ network_id >= 0): @@ -127,6 +142,7 @@ def is_valid_wired_network_id(network_id): sys.exit(4) def is_valid_wired_network_profile(profile_name): + """ Check if it's a valid wired network profile. '""" if not profile_name in wired.GetWiredProfileList(): print 'Profile of that name does not exist.' sys.exit(5) @@ -151,10 +167,10 @@ if options.list_networks: wireless.GetWirelessProperty(network_id, 'essid')) elif options.wired: print '#\tProfile name' - id = 0 + i = 0 for profile in wired.GetWiredProfileList(): - print '%s\t%s' % (id, profile) - id += 1 + print '%s\t%s' % (i, profile) + i += 1 op_performed = True if options.network_details: @@ -173,13 +189,17 @@ if options.network_details: if wireless.GetWirelessProperty(network_id, "encryption"): print "Encryption: On" print "Encryption Method: %s" % \ - wireless.GetWirelessProperty(network_id, "encryption_method") + wireless.GetWirelessProperty(network_id, "encryption_method") else: print "Encryption: Off" - print "Quality: %s" % wireless.GetWirelessProperty(network_id, "quality") - print "Mode: %s" % wireless.GetWirelessProperty(network_id, "mode") - print "Channel: %s" % wireless.GetWirelessProperty(network_id, "channel") - print "Bit Rates: %s" % wireless.GetWirelessProperty(network_id, "bitrates") + print "Quality: %s" % \ + wireless.GetWirelessProperty(network_id, "quality") + print "Mode: %s" % \ + wireless.GetWirelessProperty(network_id, "mode") + print "Channel: %s" % \ + wireless.GetWirelessProperty(network_id, "channel") + print "Bit Rates: %s" % \ + wireless.GetWirelessProperty(network_id, "bitrates") op_performed = True # network properties @@ -194,7 +214,8 @@ if options.network_property: network_id = wireless.GetCurrentNetworkID(0) is_valid_wireless_network_id(network_id) if not options.set_to: - print wireless.GetWirelessProperty(network_id, options.network_property) + print wireless.GetWirelessProperty(network_id, + options.network_property) else: wireless.SetWirelessProperty(network_id, \ options.network_property, options.set_to) @@ -209,11 +230,13 @@ if options.disconnect: daemon.Disconnect() if options.wireless: if wireless.GetCurrentNetworkID(0) > -1: - print "Disconnecting from %s on %s" % (wireless.GetCurrentNetwork(0), - wireless.DetectWirelessInterface()) + print "Disconnecting from %s on %s" % \ + (wireless.GetCurrentNetwork(0), + wireless.DetectWirelessInterface()) elif options.wired: if wired.CheckPluggedIn(): - print "Disconnecting from wired connection on %s" % wired.DetectWiredInterface() + print "Disconnecting from wired connection on %s" % \ + wired.DetectWiredInterface() op_performed = True if options.connect: @@ -226,16 +249,17 @@ if options.connect: wireless.DetectWirelessInterface()) wireless.ConnectWireless(options.network) - check = lambda: wireless.CheckIfWirelessConnecting() - status = lambda: wireless.CheckWirelessConnectingStatus() - message = lambda: wireless.CheckWirelessConnectingMessage() + check = wireless.CheckIfWirelessConnecting + status = wireless.CheckWirelessConnectingStatus + message = wireless.CheckWirelessConnectingMessage elif options.wired: - print "Connecting to wired connection on %s" % wired.DetectWiredInterface() + print "Connecting to wired connection on %s" % \ + wired.DetectWiredInterface() wired.ConnectWired() - check = lambda: wired.CheckIfWiredConnecting() - status = lambda: wired.CheckWiredConnectingStatus() - message = lambda: wired.CheckWiredConnectingMessage() + check = wired.CheckIfWiredConnecting + status = wired.CheckWiredConnectingStatus + message = wired.CheckWiredConnectingMessage else: check = lambda: False status = lambda: False @@ -245,36 +269,37 @@ if options.connect: last = None if check: while check(): - next = status() - if next != last: - # avoid a race condition where status is updated to "done" after the - # loop check - if next == "done": + next_ = status() + if next_ != last: + # avoid a race condition where status is updated to "done" after + # the loop check + if next_ == "done": break print message() - last = next + last = next_ print "done!" op_performed = True -# pretty print optional and required properties def str_properties(prop): + """ Pretty print optional and required properties. """ if len(prop) == 0: return "None" else: - return ', '.join("%s (%s)" % (x[0], x[1].replace("_", " ")) for x in type['required']) + tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']] + return ', '.join("%s (%s)" % (x, y) for x, y in tmp) if options.wireless and options.list_encryption_types: et = misc.LoadEncryptionMethods() # print 'Installed encryption templates:' print '%s\t%-20s\t%s' % ('#', 'Name', 'Description') - id = 0 - for type in et: - print '%s\t%-20s\t%s' % (id, type['type'], type['name']) - print ' Req: %s' % str_properties(type['required']) + i = 0 + for t in et: + print '%s\t%-20s\t%s' % (i, t['type'], t['name']) + print ' Req: %s' % str_properties(t['required']) print '---' # don't print optionals (yet) #print ' Opt: %s' % str_properties(type['optional']) - id += 1 + i += 1 op_performed = True if options.save and options.network > -1: diff --git a/curses/configscript_curses.py b/curses/configscript_curses.py index 9920d29..64c2ddc 100755 --- a/curses/configscript_curses.py +++ b/curses/configscript_curses.py @@ -26,26 +26,36 @@ Also recycles a lot of configscript.py, too. :-) from wicd import misc from wicd.translations import _ import configscript -from configscript import write_scripts,get_script_info,get_val,none_to_blank,blank_to_none +from configscript import write_scripts, get_script_info, get_val +from configscript import none_to_blank, blank_to_none import urwid import urwid.curses_display import sys import os +ui = None +frame = None +pre_entry = None +post_entry = None +pre_disconnect_entry = None +post_disconnect_entry = None + def main(argv): - global ui,frame + """ Main function. """ + global ui, frame if len(argv) < 2: print 'Network id to configure is missing, aborting.' sys.exit(1) ui = urwid.curses_display.Screen() - ui.register_palette( [ - ('body','default','default'), - ('focus','dark magenta','light gray'), + ui.register_palette([ + ('body', 'default', 'default'), + ('focus', 'dark magenta', 'light gray'), ('editcp', 'default', 'default', 'standout'), ('editbx', 'light gray', 'dark blue'), - ('editfc', 'white','dark blue', 'bold')] ) + ('editfc', 'white','dark blue', 'bold'), + ]) network = argv[1] network_type = argv[2] @@ -53,34 +63,44 @@ def main(argv): script_info = get_script_info(network, network_type) blank = urwid.Text('') - pre_entry_t = ('body',_('Pre-connection Script')+': ') - post_entry_t = ('body',_('Post-connection Script')+': ') - pre_disconnect_entry_t = ('body',_('Pre-disconnection Script')+': ') - post_disconnect_entry_t = ('body',_('Post-disconnection Script')+': ') + pre_entry_t = ('body', _('Pre-connection Script') + ': ') + post_entry_t = ('body', _('Post-connection Script') + ': ') + pre_disconnect_entry_t = ('body', _('Pre-disconnection Script') + ': ') + post_disconnect_entry_t = ('body', _('Post-disconnection Script') + ': ') - global pre_entry,post_entry,pre_disconnect_entry,post_disconnect_entry - pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t, - none_to_blank(script_info.get('pre_entry'))),'editbx','editfc' ) - post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, - none_to_blank(script_info.get('post_entry'))),'editbx','editfc' ) + global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry + pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t, + none_to_blank(script_info.get('pre_entry'))), + 'editbx', 'editfc') + post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, + none_to_blank(script_info.get('post_entry'))), + 'editbx','editfc') - pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, - none_to_blank(script_info.get('pre_disconnect_entry'))),'editbx','editfc' ) - post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, - none_to_blank(script_info.get('post_disconnect_entry'))),'editbx','editfc' ) + pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, + none_to_blank(script_info.get('pre_disconnect_entry'))), + 'editbx', 'editfc') + post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, + none_to_blank(script_info.get('post_disconnect_entry'))), + 'editbx','editfc') # The buttons - ok_button = urwid.AttrWrap(urwid.Button(_('OK'),ok_callback),'body','focus') - cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'),cancel_callback),'body','focus') + ok_button = urwid.AttrWrap( + urwid.Button(_('OK'), ok_callback), + 'body','focus' + ) + cancel_button = urwid.AttrWrap( + urwid.Button(_('Cancel'), cancel_callback), + 'body','focus' + ) - button_cols = urwid.Columns([ok_button,cancel_button],dividechars=1) + button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1) - lbox = urwid.Pile([('fixed',2,urwid.Filler(pre_entry)), - #('fixed',urwid.Filler(blank),1), - ('fixed',2,urwid.Filler(post_entry)), - ('fixed',2,urwid.Filler(pre_disconnect_entry)), - ('fixed',2,urwid.Filler(post_disconnect_entry)), - #blank,blank,blank,blank,blank, + lbox = urwid.Pile([('fixed', 2, urwid.Filler(pre_entry)), + #('fixed', urwid.Filler(blank), 1), + ('fixed', 2, urwid.Filler(post_entry)), + ('fixed', 2, urwid.Filler(pre_disconnect_entry)), + ('fixed', 2, urwid.Filler(post_disconnect_entry)), + #blank, blank, blank, blank, blank, urwid.Filler(button_cols,'bottom') ]) frame = urwid.Frame(lbox) @@ -89,16 +109,18 @@ def main(argv): if result == True: script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text()) script_info["post_entry"] = blank_to_none(post_entry.get_edit_text()) - script_info["pre_disconnect_entry"] = blank_to_none(pre_disconnect_entry.get_edit_text()) - script_info["post_disconnect_entry"] = blank_to_none(post_disconnect_entry.get_edit_text()) + script_info["pre_disconnect_entry"] = \ + blank_to_none(pre_disconnect_entry.get_edit_text()) + script_info["post_disconnect_entry"] = \ + blank_to_none(post_disconnect_entry.get_edit_text()) write_scripts(network, network_type, script_info) OK_PRESSED = False CANCEL_PRESSED = False -def ok_callback(button_object,user_data=None): +def ok_callback(button_object, user_data=None): global OK_PRESSED OK_PRESSED = True -def cancel_callback(button_object,user_data=None): +def cancel_callback(button_object, user_data=None): global CANCEL_PRESSED CANCEL_PRESSED = True def run(): @@ -119,9 +141,7 @@ def run(): #Send key to underlying widget: if urwid.is_mouse_event(k): event, button, col, row = k - frame.mouse_event( dim, - event, button, col, row, - focus=True) + frame.mouse_event(dim, event, button, col, row, focus=True) else: frame.keypress(dim, k) # Check if buttons are pressed. diff --git a/curses/curses_misc.py b/curses/curses_misc.py index 925c34b..1bd30b6 100644 --- a/curses/curses_misc.py +++ b/curses/curses_misc.py @@ -27,13 +27,13 @@ import urwid from wicd.translations import _ # Uses code that is towards the bottom -def error(ui,parent,message): +def error(ui, parent, message): """Shows an error dialog (or something that resembles one)""" # /\ # /!!\ # /____\ - dialog = TextDialog(message,6,40,('important',"ERROR")) - return dialog.run(ui,parent) + dialog = TextDialog(message, 6, 40, ('important', 'ERROR')) + return dialog.run(ui, parent) class SelText(urwid.Text): """A selectable text widget. See urwid.Text.""" @@ -42,13 +42,12 @@ class SelText(urwid.Text): """Make widget selectable.""" return True - def keypress(self, size, key): """Don't handle any keys.""" return key -# ListBox that can't be selected. class NSelListBox(urwid.ListBox): + """ Non-selectable ListBox. """ def selectable(self): return False @@ -64,8 +63,9 @@ class DynWrap(urwid.AttrWrap): attrfoc = attributes when in focus, defaults to nothing """ - def __init__(self,w,sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'): - self._attrs=attrs + def __init__(self, w, sensitive=True, attrs=('editbx', 'editnfc'), \ + focus_attr='editfc'): + self._attrs = attrs self._sensitive = sensitive if sensitive: @@ -73,48 +73,59 @@ class DynWrap(urwid.AttrWrap): else: cur_attr = attrs[1] - self.__super.__init__(w,cur_attr,focus_attr) + self.__super.__init__(w, cur_attr, focus_attr) def get_sensitive(self): + """ Getter for sensitive property. """ return self._sensitive - def set_sensitive(self,state): + def set_sensitive(self, state): + """ Setter for sensitive property. """ if state: self.set_attr(self._attrs[0]) else: self.set_attr(self._attrs[1]) self._sensitive = state - property(get_sensitive,set_sensitive) + property(get_sensitive, set_sensitive) def get_attrs(self): + """ Getter for attrs property. """ return self._attrs - def set_attrs(self,attrs): + def set_attrs(self, attrs): + """ Setter for attrs property. """ self._attrs = attrs - property(get_attrs,set_attrs) + property(get_attrs, set_attrs) def selectable(self): return self._sensitive -# Just an Edit Dynwrapped to the most common specifications class DynEdit(DynWrap): - def __init__(self,caption='',edit_text='',sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'): - caption = ('editcp',caption + ': ') - edit = urwid.Edit(caption,edit_text) - self.__super.__init__(edit,sensitive,attrs,focus_attr) + """ Edit DynWrap'ed to the most common specifications. """ + def __init__(self, caption='', edit_text='', sensitive=True, + attrs=('editbx', 'editnfc'), focus_attr='editfc'): + caption = ('editcp', caption + ': ') + edit = urwid.Edit(caption, edit_text) + self.__super.__init__(edit, sensitive, attrs, focus_attr) -# Just an IntEdit Dynwrapped to the most common specifications class DynIntEdit(DynWrap): - def __init__(self,caption='',edit_text='',sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'): - caption = ('editcp',caption + ':') - edit = urwid.IntEdit(caption,edit_text) - self.__super.__init__(edit,sensitive,attrs,focus_attr) + """ IntEdit DynWrap'ed to the most common specifications. """ + def __init__(self, caption='', edit_text='', sensitive=True, + attrs=('editbx', 'editnfc'), focus_attr='editfc'): + caption = ('editcp', caption + ':') + edit = urwid.IntEdit(caption, edit_text) + self.__super.__init__(edit, sensitive, attrs, focus_attr) class DynRadioButton(DynWrap): - def __init__(self,group,label,state='first True',on_state_change=None, user_data=None, sensitive=True, attrs=('body','editnfc'),focus_attr='body'): - #caption = ('editcp',caption + ':') - button = urwid.RadioButton(group,label,state,on_state_change,user_data) - self.__super.__init__(button,sensitive,attrs,focus_attr) + """ RadioButton DynWrap'ed to the most common specifications. """ + def __init__(self, group, label, state='first True', on_state_change=None, + user_data=None, sensitive=True, attrs=('body', 'editnfc'), + focus_attr='body'): + #caption = ('editcp', caption + ':') + button = urwid.RadioButton(group, label, state, on_state_change, + user_data) + self.__super.__init__(button, sensitive, attrs, focus_attr) class MaskingEditException(Exception): + """ Custom exception. """ pass # Password-style edit @@ -131,29 +142,31 @@ class MaskingEdit(urwid.Edit): edit_pos = None, layout=None, mask_mode="always",mask_char='*'): self.mask_mode = mask_mode if len(mask_char) > 1: - raise MaskingEditException('Masks of more than one character are not supported!') + raise MaskingEditException('Masks of more than one character are' +\ + ' not supported!') self.mask_char = mask_char - self.__super.__init__(caption,edit_text,multiline,align,wrap,allow_tab,edit_pos,layout) + self.__super.__init__(caption, edit_text, multiline, align, wrap, + allow_tab, edit_pos, layout) def get_caption(self): return self.caption def get_mask_mode(self): return self.mask_mode - def set_mask_mode(self,mode): + def set_mask_mode(self, mode): self.mask_mode = mode def get_masked_text(self): return self.mask_char*len(self.get_edit_text()) - def render(self,(maxcol,), focus=False): + def render(self, (maxcol, ), focus=False): """ Render edit widget and return canvas. Include cursor when in focus. """ # If we aren't masking anything ATM, then act like an Edit. # No problems. - if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus == True): - canv = self.__super.render((maxcol,),focus) + if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus): + canv = self.__super.render((maxcol, ), focus) # The cache messes this thing up, because I am totally changing what # is displayed. self._invalidate() @@ -163,49 +176,50 @@ class MaskingEdit(urwid.Edit): self._shift_view_to_cursor = not not focus # force bool text, attr = self.get_text() - text = text[:len(self.caption)]+self.get_masked_text() - trans = self.get_line_translation( maxcol, (text,attr) ) + text = text[:len(self.caption)] + self.get_masked_text() + trans = self.get_line_translation(maxcol, (text, attr)) canv = urwid.canvas.apply_text_layout(text, attr, trans, maxcol) if focus: canv = urwid.CompositeCanvas(canv) - canv.cursor = self.get_cursor_coords((maxcol,)) + canv.cursor = self.get_cursor_coords((maxcol, )) return canv -# Tabbed interface, mostly for use in the Preferences Dialog class TabColumns(urwid.WidgetWrap): """ + Tabbed interface, mostly for use in the Preferences Dialog + titles_dict = dictionary of tab_contents (a SelText) : tab_widget (box) attr = normal attributes attrsel = attribute when active """ # FIXME Make the bottom_part optional - def __init__(self,tab_str,tab_wid,title,bottom_part=None,attr=('body','focus'), - attrsel='tab active', attrtitle='header'): + def __init__(self, tab_str, tab_wid, title, bottom_part=None, + attr=('body', 'focus'), attrsel='tab active', attrtitle='header'): #self.bottom_part = bottom_part - #title_wid = urwid.Text((attrtitle,title),align='right') + #title_wid = urwid.Text((attrtitle, title), align='right') column_list = [] for w in tab_str: - text,trash = w.get_text() - column_list.append(('fixed',len(text),w)) - column_list.append(urwid.Text((attrtitle,title),align='right')) + text, _ = w.get_text() + column_list.append(('fixed', len(text), w)) + column_list.append(urwid.Text((attrtitle, title), align='right')) - self.tab_map = dict(zip(tab_str,tab_wid)) + self.tab_map = dict(zip(tab_str, tab_wid)) self.active_tab = tab_str[0] - self.columns = urwid.Columns(column_list,dividechars=1) - #walker = urwid.SimpleListWalker([self.columns,tab_wid[0]]) + self.columns = urwid.Columns(column_list, dividechars=1) + #walker = urwid.SimpleListWalker([self.columns, tab_wid[0]]) #self.listbox = urwid.ListBox(walker) - self.gen_pile(tab_wid[0],True) + self.gen_pile(tab_wid[0], True) self.frame = urwid.Frame(self.pile) self.__super.__init__(self.frame) - - # Make the pile in the middle - def gen_pile(self,lbox,firstrun=False): + + def gen_pile(self, lbox, firstrun=False): + """ Make the pile in the middle. """ self.pile = urwid.Pile([ - ('fixed',1,urwid.Filler(self.columns,'top')), - urwid.Filler(lbox,'top',height=('relative',99)), - #('fixed',1,urwid.Filler(self.bottom_part,'bottom')) + ('fixed', 1, urwid.Filler(self.columns, 'top')), + urwid.Filler(lbox, 'top', height=('relative', 99)), + #('fixed', 1, urwid.Filler(self.bottom_part, 'bottom')) ]) if not firstrun: self.frame.set_body(self.pile) @@ -213,9 +227,11 @@ class TabColumns(urwid.WidgetWrap): self._invalidate() def selectable(self): + """ Return whether the widget is selectable. """ return True - def keypress(self,size,key): + def keypress(self, size, key): + """ Handle keypresses. """ # If the key is page up or page down, move focus to the tabs and call # left or right on the tabs. if key == "page up" or key == "page down": @@ -224,25 +240,26 @@ class TabColumns(urwid.WidgetWrap): newK = 'left' else: newK = 'right' - self.keypress(size,newK) + self.keypress(size, newK) self._w.get_body().set_focus(1) else: - key = self._w.keypress(size,key) + key = self._w.keypress(size, key) wid = self.pile.get_focus().get_body() if wid == self.columns: self.active_tab.set_attr('body') self.columns.get_focus().set_attr('tab active') self.active_tab = self.columns.get_focus() self.gen_pile(self.tab_map[self.active_tab]) - + return key - def mouse_event(self,size,event,button,x,y,focus): + def mouse_event(self, size, event, button, x, y, focus): + """ Handle mouse events. """ wid = self.pile.get_focus().get_body() if wid == self.columns: self.active_tab.set_attr('body') - self._w.mouse_event(size,event,button,x,y,focus) + self._w.mouse_event(size, event, button, x, y, focus) if wid == self.columns: self.active_tab.set_attr('body') self.columns.get_focus().set_attr('tab active') @@ -250,8 +267,8 @@ class TabColumns(urwid.WidgetWrap): self.gen_pile(self.tab_map[self.active_tab]) -### Combo box code begins here class ComboBoxException(Exception): + """ Custom exception. """ pass # A "combo box" of SelTexts @@ -264,10 +281,11 @@ class ComboBox(urwid.WidgetWrap): """A ComboBox of text objects""" class ComboSpace(urwid.WidgetWrap): """The actual menu-like space that comes down from the ComboBox""" - def __init__(self,list,body,ui,show_first,pos=(0,0),attr=('body','focus')): + def __init__(self, l, body, ui, show_first, pos=(0, 0), + attr=('body', 'focus')): """ body : parent widget - list : stuff to include in the combobox + l : stuff to include in the combobox ui : the screen show_first: index of the element in the list to pick first pos : a tuple of (row,col) where to put the list @@ -275,13 +293,13 @@ class ComboBox(urwid.WidgetWrap): """ #Calculate width and height of the menu widget: - height = len(list) + height = len(l) width = 0 - for entry in list: + for entry in l: if len(entry) > width: width = len(entry) content = [urwid.AttrWrap(SelText(w), attr[0], attr[1]) - for w in list] + for w in l] self._listbox = urwid.ListBox(content) self._listbox.set_focus(show_first) @@ -289,8 +307,8 @@ class ComboBox(urwid.WidgetWrap): width + 2, ('fixed top', pos[1]), height) self.__super.__init__(overlay) - def show(self,ui,display): - + def show(self, ui, display): + """ Show widget. """ dim = ui.get_cols_rows() keys = True @@ -298,7 +316,7 @@ class ComboBox(urwid.WidgetWrap): while True: if keys: ui.draw_screen(dim, self.render(dim, True)) - + keys = ui.get_input() if "window resize" in keys: @@ -306,8 +324,8 @@ class ComboBox(urwid.WidgetWrap): if "esc" in keys: return None if "enter" in keys: - (wid,pos) = self._listbox.get_focus() - (text,attr) = wid.get_text() + (wid, pos) = self._listbox.get_focus() + (text, attr) = wid.get_text() return text for k in keys: @@ -316,11 +334,13 @@ class ComboBox(urwid.WidgetWrap): #def get_size(self): - def __init__(self,label='',list=[],attrs=('body','editnfc'),focus_attr='focus',use_enter=True,focus=0,callback=None,user_args=None): + def __init__(self, label='', l=[], attrs=('body', 'editnfc'), + focus_attr='focus', use_enter=True, focus=0, callback=None, + user_args=None): """ label : bit of text that preceeds the combobox. If it is "", then ignore it - list : stuff to include in the combobox + l : stuff to include in the combobox body : parent widget ui : the screen row : where this object is to be found onscreen @@ -333,15 +353,19 @@ class ComboBox(urwid.WidgetWrap): self.label = urwid.Text(label) self.attrs = attrs self.focus_attr = focus_attr - self.list = list + self.list = l - str,trash = self.label.get_text() + s, _ = self.label.get_text() self.overlay = None - self.cbox = DynWrap(SelText(self.DOWN_ARROW),attrs=attrs,focus_attr=focus_attr) + self.cbox = DynWrap(SelText(self.DOWN_ARROW), attrs=attrs, + focus_attr=focus_attr) # Unicode will kill me sooner or later. if label != '': - w = urwid.Columns([('fixed',len(str),self.label),self.cbox],dividechars=1) + w = urwid.Columns( + [('fixed', len(s), self.label), self.cbox], + dividechars=1 + ) else: w = urwid.Columns([self.cbox]) self.__super.__init__(w) @@ -361,10 +385,11 @@ class ComboBox(urwid.WidgetWrap): self.parent = None self.ui = None self.row = None - def set_list(self,list): - self.list = list - def set_focus(self,index): + def set_list(self, l): + self.list = l + + def set_focus(self, index): if urwid.VERSION < (1, 1, 0): self.focus = index else: @@ -375,33 +400,34 @@ class ComboBox(urwid.WidgetWrap): # API changed between urwid 0.9.8.4 and 0.9.9 try: - self.cbox.set_w(SelText(self.list[index]+self.DOWN_ARROW)) + self.cbox.set_w(SelText(self.list[index] + self.DOWN_ARROW)) except AttributeError: - self.cbox._w = SelText(self.list[index]+self.DOWN_ARROW) + self.cbox._w = SelText(self.list[index] + self.DOWN_ARROW) if self.overlay: self.overlay._listbox.set_focus(index) def rebuild_combobox(self): - self.build_combobox(self.parent,self.ui,self.row) - def build_combobox(self,parent,ui,row): - str,trash = self.label.get_text() + self.build_combobox(self.parent, self.ui, self.row) + + def build_combobox(self, parent, ui, row): + s, _ = self.label.get_text() if urwid.VERSION < (1, 1, 0): index = self.focus else: index = self._w.focus_position - self.cbox = DynWrap(SelText([self.list[index]+self.DOWN_ARROW]), - attrs=self.attrs,focus_attr=self.focus_attr) + self.cbox = DynWrap(SelText([self.list[index] + self.DOWN_ARROW]), + attrs=self.attrs, focus_attr=self.focus_attr) if str != '': - w = urwid.Columns([('fixed',len(str),self.label),self.cbox], - dividechars=1) - self.overlay = self.ComboSpace(self.list,parent,ui,index, - pos=(len(str)+1,row)) + w = urwid.Columns([('fixed', len(s), self.label), self.cbox], + dividechars=1) + self.overlay = self.ComboSpace(self.list, parent, ui, index, + pos=(len(s) + 1, row)) else: w = urwid.Columns([self.cbox]) - self.overlay = self.ComboSpace(self.list,parent,ui,index, - pos=(0,row)) + self.overlay = self.ComboSpace(self.list, parent, ui, index, + pos=(0, row)) self._w = w self._invalidate() @@ -410,7 +436,7 @@ class ComboBox(urwid.WidgetWrap): self.row = row # If we press space or enter, be a combo box! - def keypress(self,size,key): + def keypress(self, size, key): activate = key == ' ' if self.use_enter: activate = activate or key == 'enter' @@ -418,14 +444,14 @@ class ComboBox(urwid.WidgetWrap): # Die if the user didn't prepare the combobox overlay if self.overlay == None: raise ComboBoxException('ComboBox must be built before use!') - retval = self.overlay.show(self.ui,self.parent) + retval = self.overlay.show(self.ui, self.parent) if retval != None: self.set_focus(self.list.index(retval)) #self.cbox.set_w(SelText(retval+' vvv')) if self.callback != None: - self.callback(self,self.overlay._listbox.get_focus()[1], - self.user_args) - return self._w.keypress(size,key) + self.callback(self, self.overlay._listbox.get_focus()[1], + self.user_args) + return self._w.keypress(size, key) def selectable(self): return self.cbox.selectable() @@ -441,7 +467,7 @@ class ComboBox(urwid.WidgetWrap): def get_sensitive(self): return self.cbox.get_sensitive() - def set_sensitive(self,state): + def set_sensitive(self, state): self.cbox.set_sensitive(state) # This is a h4x3d copy of some of the code in Ian Ward's dialog.py example. @@ -449,54 +475,60 @@ class DialogExit(Exception): pass class Dialog2(urwid.WidgetWrap): - def __init__(self, text, height,width, body=None ): - self.width = int(width) - if width <= 0: - self.width = ('relative', 80) - self.height = int(height) - if height <= 0: - self.height = ('relative', 80) - - self.body = body - if body is None: - # fill space with nothing - body = urwid.Filler(urwid.Divider(),'top') - - self.frame = urwid.Frame( body, focus_part='footer') - if text is not None: - self.frame.header = urwid.Pile( [urwid.Text(text,align='right'), - urwid.Divider()] ) - w = self.frame - self.view = w + def __init__(self, text, height, width, body=None ): + self.width = int(width) + if width <= 0: + self.width = ('relative', 80) + self.height = int(height) + if height <= 0: + self.height = ('relative', 80) + + self.body = body + if body is None: + # fill space with nothing + body = urwid.Filler(urwid.Divider(), 'top') + + self.frame = urwid.Frame(body, focus_part='footer') + if text is not None: + self.frame.header = urwid.Pile([ + urwid.Text(text, align='right'), + urwid.Divider() + ]) + w = self.frame + self.view = w # buttons: tuple of name,exitcode def add_buttons(self, buttons): l = [] maxlen = 0 for name, exitcode in buttons: - b = urwid.Button( name, self.button_press ) + b = urwid.Button(name, self.button_press) b.exitcode = exitcode - b = urwid.AttrWrap( b, 'body','focus' ) - l.append( b ) + b = urwid.AttrWrap(b, 'body', 'focus') + l.append(b) maxlen = max(len(name), maxlen) maxlen += 4 # because of '< ... >' self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center') - self.frame.footer = urwid.Pile( [ urwid.Divider(), - self.buttons ], focus_item = 1) + self.frame.footer = urwid.Pile([ + urwid.Divider(), + self.buttons + ], focus_item=1) def button_press(self, button): raise DialogExit(button.exitcode) - def run(self,ui,parent): + def run(self, ui, parent): ui.set_mouse_tracking() size = ui.get_cols_rows() - overlay = urwid.Overlay(urwid.LineBox(self.view), - parent, 'center', self.width, - 'middle', self.height) + overlay = urwid.Overlay( + urwid.LineBox(self.view), + parent, 'center', self.width, + 'middle', self.height + ) try: while True: - canvas = overlay.render( size, focus=True ) - ui.draw_screen( size, canvas ) + canvas = overlay.render(size, focus=True) + ui.draw_screen(size, canvas) keys = None while not keys: keys = ui.get_input() @@ -507,19 +539,18 @@ class Dialog2(urwid.WidgetWrap): check_mouse_event = urwid.util.is_mouse_event if check_mouse_event(k): event, button, col, row = k - overlay.mouse_event( size, - event, button, col, row, - focus=True) + overlay.mouse_event(size, event, button, col, row, + focus=True) else: if k == 'window resize': size = ui.get_cols_rows() - k = self.view.keypress( size, k ) + k = self.view.keypress(size, k) if k == 'esc': raise DialogExit(-1) if k: - self.unhandled_key( size, k) + self.unhandled_key(size, k) except DialogExit, e: - return self.on_exit( e.args[0] ) + return self.on_exit(e.args[0]) def on_exit(self, exitcode): return exitcode, "" @@ -535,50 +566,50 @@ class TextDialog(Dialog2): body = urwid.ListBox(l) body = urwid.AttrWrap(body, 'body') - Dialog2.__init__(self, header, height+2, width+2, body) + Dialog2.__init__(self, header, height + 2, width + 2, body) if type(buttons) == list: self.add_buttons(buttons) else: self.add_buttons([buttons]) def unhandled_key(self, size, k): - if k in ('up','page up','down','page down'): + if k in ('up', 'page up', 'down', 'page down'): self.frame.set_focus('body') self.view.keypress( size, k ) self.frame.set_focus('footer') class InputDialog(Dialog2): - def __init__(self, text, height, width,ok_name=_('OK'),edit_text=''): - self.edit = urwid.Edit(wrap='clip',edit_text=edit_text) + def __init__(self, text, height, width, ok_name=_('OK'), edit_text=''): + self.edit = urwid.Edit(wrap='clip', edit_text=edit_text) body = urwid.ListBox([self.edit]) - body = urwid.AttrWrap(body, 'editbx','editfc') + body = urwid.AttrWrap(body, 'editbx', 'editfc') Dialog2.__init__(self, text, height, width, body) self.frame.set_focus('body') - self.add_buttons([(ok_name,0),(_('Cancel'),-1)]) + self.add_buttons([(ok_name, 0), (_('Cancel'), -1)]) def unhandled_key(self, size, k): - if k in ('up','page up'): + if k in ('up', 'page up'): self.frame.set_focus('body') - if k in ('down','page down'): + if k in ('down', 'page down'): self.frame.set_focus('footer') if k == 'enter': # pass enter to the "ok" button self.frame.set_focus('footer') - self.view.keypress( size, k ) + self.view.keypress(size, k) def on_exit(self, exitcode): return exitcode, self.edit.get_edit_text() class ClickCols(urwid.WidgetWrap): - def __init__(self,items,callback=None,args=None): + def __init__(self, items, callback=None, args=None): cols = urwid.Columns(items) self.__super.__init__(cols) self.callback = callback self.args = args - def mouse_event(self,size,event,button,x,y,focus): + def mouse_event(self, size, event, button, x, y, focus): if event == "mouse press": # The keypress dealie in wicd-curses.py expects a list of keystrokes self.callback([self.args]) @@ -589,7 +620,7 @@ class OptCols(urwid.WidgetWrap): # attrs = (attr_key,attr_desc) # handler = function passed the key of the "button" pressed # mentions of 'left' and right will be converted to <- and -> respectively - def __init__(self,tuples,handler,attrs=('body','infobar'),debug=False): + def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False): # Find the longest string. Keys for this bar should be no greater than # 2 characters long (e.g., -> for left) #maxlen = 6 @@ -604,12 +635,12 @@ class OptCols(urwid.WidgetWrap): # callbacks map the text contents to its assigned callback. self.callbacks = [] for cmd in tuples: - key = reduce(lambda s,(f,t):s.replace(f,t), [ \ + key = reduce(lambda s, (f, t): s.replace(f, t), [ \ ('ctrl ', 'Ctrl+'), ('meta ', 'Alt+'), \ ('left', '<-'), ('right', '->'), \ ('page up', 'Page Up'), ('page down', 'Page Down'), \ ('esc', 'ESC'), ('enter', 'Enter'), ('f10','F10')], cmd[0]) - + if debug: callback = self.debugClick args = cmd[1] @@ -618,20 +649,20 @@ class OptCols(urwid.WidgetWrap): args = cmd[0] #self.callbacks.append(cmd[2]) col = ClickCols([ - ('fixed',len(key)+1,urwid.Text((attrs[0],key+':')) ), - urwid.AttrWrap(urwid.Text(cmd[1]),attrs[1])], - callback,args) + ('fixed', len(key) + 1, urwid.Text((attrs[0], key + ':'))), + urwid.AttrWrap(urwid.Text(cmd[1]), attrs[1])], + callback, args) textList.append(col) - i+=1 + i += 1 if debug: self.debug = urwid.Text("DEBUG_MODE") - textList.append(('fixed',10,self.debug)) + textList.append(('fixed', 10, self.debug)) cols = urwid.Columns(textList) self.__super.__init__(cols) - def debugClick(self,args): + def debugClick(self, args): self.debug.set_text(args) - def mouse_event(self,size,event,button,x,y,focus): + def mouse_event(self, size, event, button, x, y, focus): # Widgets are evenly long (as of current), so... - return self._w.mouse_event(size,event,button,x,y,focus) + return self._w.mouse_event(size, event, button, x, y, focus) diff --git a/in/wicd=wpath.py.in b/in/wicd=wpath.py.in index d4a04cd..8df15c9 100755 --- a/in/wicd=wpath.py.in +++ b/in/wicd=wpath.py.in @@ -46,7 +46,7 @@ dbus_service = '%DBUS_SERVICE%' systemd = '%SYSTEMD%' logrotate = '%LOGROTATE%' desktop = '%DESKTOP%' -backends= '%BACKENDS%' +backends = '%BACKENDS%' daemon = '%DAEMON%' curses = '%CURSES%' gtk = '%GTK%' @@ -88,12 +88,12 @@ no_install_ncurses = %NO_INSTALL_NCURSES% no_install_cli = %NO_INSTALL_CLI% no_use_notifications = %NO_USE_NOTIFICATIONS% -def chdir(file): +def chdir(f): """Change directory to the location of the specified file. Keyword arguments: - file -- the file to switch to (usually __file__) + f -- the file to switch to (usually __file__) """ - os.chdir(os.path.dirname(os.path.realpath(file))) + os.chdir(os.path.dirname(os.path.realpath(f))) diff --git a/wicd/__init__.py b/wicd/__init__.py index e69de29..9b51119 100644 --- a/wicd/__init__.py +++ b/wicd/__init__.py @@ -0,0 +1 @@ +""" WICD core module. """ diff --git a/wicd/autoconnect.py b/wicd/autoconnect.py index 8d9550c..7b1fe43 100755 --- a/wicd/autoconnect.py +++ b/wicd/autoconnect.py @@ -36,14 +36,16 @@ try: daemon = dbusmanager.get_interface('daemon') wireless = dbusmanager.get_interface('wireless') except Exception, e: - print>>sys.stderr, "Exception caught: %s" % str(e) - print>>sys.stderr, 'Could not connect to daemon.' + print >> sys.stderr, "Exception caught: %s" % str(e) + print >> sys.stderr, 'Could not connect to daemon.' sys.exit(1) def handler(*args): + """ No-op handler. """ pass def error_handler(*args): - print>>sys.stderr, 'Async error autoconnecting.' + """ Error handler. """ + print >> sys.stderr, 'Async error autoconnecting.' sys.exit(3) if __name__ == '__main__': @@ -54,6 +56,6 @@ if __name__ == '__main__': daemon.AutoConnect(True, reply_handler=handler, error_handler=error_handler) except Exception, e: - print>>sys.stderr, "Exception caught: %s" % str(e) - print>>sys.stderr, 'Error autoconnecting.' + print >> sys.stderr, "Exception caught: %s" % str(e) + print >> sys.stderr, 'Error autoconnecting.' sys.exit(2) diff --git a/wicd/backend.py b/wicd/backend.py index 15b4a7a..bf4f220 100644 --- a/wicd/backend.py +++ b/wicd/backend.py @@ -30,6 +30,7 @@ import os import wicd.wpath as wpath def fail(backend_name, reason): + """ Helper to warn the user about failure in loading backend. """ print "Failed to load backend %s: %s" % (backend_name, reason) return True @@ -40,7 +41,7 @@ class BackendManager(object): """ Initialize the backend manager. """ self.backend_dir = wpath.backends self.__loaded_backend = None - + def _valid_backend_file(self, be_file): """ Make sure the backend file is valid. """ return (os.path.exists(be_file) and @@ -115,7 +116,8 @@ class BackendManager(object): """ backend = self._load_backend(backend_name) - if not backend : return None + if not backend: + return None failed = self._validate_backend(backend, backend_name) if failed: diff --git a/wicd/backends/__init__.py b/wicd/backends/__init__.py index e69de29..e3b4204 100644 --- a/wicd/backends/__init__.py +++ b/wicd/backends/__init__.py @@ -0,0 +1 @@ +""" Backends module. """ diff --git a/wicd/backends/be-ioctl.py b/wicd/backends/be-ioctl.py index 44aabea..d57cad8 100644 --- a/wicd/backends/be-ioctl.py +++ b/wicd/backends/be-ioctl.py @@ -155,7 +155,7 @@ class Interface(BaseInterface): return socket.inet_ntoa(raw_ip[20:24]) @neediface(False) - def IsUp(self): + def IsUp(self, ifconfig=None): """ Determines if the interface is up. Returns: @@ -357,7 +357,8 @@ class WirelessInterface(Interface, BaseWirelessInterface): print "Couldn't open ctrl_interface: %s" % e return None else: - print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" % self.iface + print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" \ + % self.iface return None def ValidateAuthentication(self, auth_time): @@ -402,7 +403,8 @@ class WirelessInterface(Interface, BaseWirelessInterface): return False if self.verbose: - print 'wpa_supplicant ctrl_interface status query is %s' % str(status) + print 'wpa_supplicant ctrl_interface status query is %s' \ + % str(status) try: [result] = [l for l in status if l.startswith("wpa_state=")] @@ -456,7 +458,8 @@ class WirelessInterface(Interface, BaseWirelessInterface): print 'Setting up WEP' cmd = ''.join(['iwconfig ', self.iface, ' key ', network.get('key')]) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) else: if info[5] == 'SHARED' and info[4] == 'WEP': @@ -488,7 +491,8 @@ class WirelessInterface(Interface, BaseWirelessInterface): for cmd in cmd_list: cmd = 'iwpriv ' + self.iface + ' ' - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface("") diff --git a/wicd/configmanager.py b/wicd/configmanager.py index 919e0e3..01dc58b 100644 --- a/wicd/configmanager.py +++ b/wicd/configmanager.py @@ -35,6 +35,7 @@ from wicd.misc import Noneify, to_unicode from dbus import Int32 def sanitize_config_file(path): + """ Remove invalid lines from config file. """ conf = open(path) newconf = '' for line in conf: @@ -56,7 +57,7 @@ class ConfigManager(RawConfigParser): sanitize_config_file(path) try: self.read(path) - except ParsingError, e: + except ParsingError: self.write() try: self.read(path) @@ -121,15 +122,18 @@ class ConfigManager(RawConfigParser): if default: if self.debug: # mask out sensitive information - if option in ['apsk', 'password', 'identity', 'private_key', \ - 'private_key_passwd', 'key', 'passphrase']: - print ''.join(['found ', option, ' in configuration *****']) + if option in ['apsk', 'password', 'identity', \ + 'private_key', 'private_key_passwd', \ + 'key', 'passphrase']: + print ''.join(['found ', option, \ + ' in configuration *****']) else: - print ''.join(['found ', option, ' in configuration ', + print ''.join(['found ', option, ' in configuration ', str(ret)]) else: if default != "__None__": - print 'did not find %s in configuration, setting default %s' % (option, str(default)) + print 'did not find %s in configuration, setting default %s' \ + % (option, str(default)) self.set(section, option, str(default), write=True) ret = default else: @@ -196,7 +200,8 @@ class ConfigManager(RawConfigParser): p = RawConfigParser() p.readfp(codecs.open(fname, 'r', 'utf-8')) for section_name in p.sections(): - # New files override old, so remove first to avoid DuplicateSectionError. + # New files override old, so remove first to avoid + # DuplicateSectionError. self.remove_section(section_name) self.add_section(section_name) for (name, value) in p.items(section_name): @@ -206,6 +211,7 @@ class ConfigManager(RawConfigParser): def _copy_section(self, name): + """ Copy whole section from config file. """ p = ConfigManager("", self.debug, self.mrk_ws) p.add_section(name) for (iname, value) in self.items(name): @@ -215,7 +221,7 @@ class ConfigManager(RawConfigParser): p.remove_option(name, '_filename_') return p - def write(self): + def write(self, fp): """ Writes the loaded config file to disk. """ in_this_file = [] for sname in sorted(self.sections()): diff --git a/wicd/dbusmanager.py b/wicd/dbusmanager.py index 17e9e0c..ecd511f 100644 --- a/wicd/dbusmanager.py +++ b/wicd/dbusmanager.py @@ -33,21 +33,27 @@ else: DBUS_MANAGER = None def get_dbus_ifaces(): + """ Return available DBus interfaces. """ return DBUS_MANAGER.get_dbus_ifaces() def get_interface(iface): + """ Return specified interface. """ return DBUS_MANAGER.get_interface(iface) def get_bus(): + """ Return the loaded System Bus. """ return DBUS_MANAGER.get_bus() -def set_mainloop(): - return DBUS_MANAGER.set_mainloop() +def set_mainloop(loop): + """ Set DBus main loop. """ + return DBUS_MANAGER.set_mainloop(loop) def connect_to_dbus(): + """ Connect to DBus. """ return DBUS_MANAGER.connect_to_dbus() def threads_init(): + """ Init GLib threads. """ dbus.mainloop.glib.threads_init() @@ -59,12 +65,14 @@ class DBusManager(object): def get_dbus_ifaces(self): """ Returns a dict of dbus interfaces. """ - if not self._dbus_ifaces: connect_to_dbus() + if not self._dbus_ifaces: + connect_to_dbus() return self._dbus_ifaces def get_interface(self, iface): """ Returns a DBus Interface. """ - if not self._dbus_ifaces: connect_to_dbus() + if not self._dbus_ifaces: + connect_to_dbus() return self._dbus_ifaces[iface] def get_bus(self): @@ -72,6 +80,7 @@ class DBusManager(object): return self._bus def set_mainloop(self, loop): + """ Set DBus main loop. """ dbus.set_default_main_loop(loop) def connect_to_dbus(self): @@ -90,4 +99,4 @@ class DBusManager(object): self._dbus_ifaces = {"daemon" : daemon, "wireless" : wireless, "wired" : wired} -DBUS_MANAGER = DBusManager() \ No newline at end of file +DBUS_MANAGER = DBusManager() diff --git a/wicd/logfile.py b/wicd/logfile.py index 7a8a27d..93e87d0 100644 --- a/wicd/logfile.py +++ b/wicd/logfile.py @@ -26,6 +26,7 @@ import os import time class SizeError(IOError): + """ Custom error class. """ pass class LogFile(file): @@ -48,7 +49,8 @@ class LogFile(file): self.written += len(data) data = data.decode('utf-8').encode('utf-8') - if len(data) <= 0: return + if len(data) <= 0: + return if self.eol: super(LogFile, self).write(self.get_time() + ' :: ') self.eol = False @@ -79,6 +81,7 @@ class LogFile(file): str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')]) def rotate(self): + """ Rotate logfile. """ return rotate(self) def note(self, text): @@ -108,21 +111,25 @@ class ManagedLog(object): self._lf.maxsize, self.maxsave) def write(self, data): + """ Write logfile. """ try: self._lf.write(data) except SizeError: self._lf = rotate(self._lf, self.maxsave) def note(self, data): + """ Write a note to the logfile. """ try: self._lf.note(data) except SizeError: self._lf = rotate(self._lf, self.maxsave) def written(self): + """ Return whether the logfile was written. """ return self._lf.written - def rotate(self): + def rotate(self): + """ Rotate logfile. """ self._lf = rotate(self._lf, self.maxsave) # auto-delegate remaining methods (but you should not read or seek an open @@ -133,7 +140,9 @@ class ManagedLog(object): # useful for logged stdout for daemon processes class ManagedStdio(ManagedLog): + """ Manage stdout/stderr. """ def write(self, data): + """ Write logfile to disk. """ try: self._lf.write(data) except SizeError: @@ -147,6 +156,7 @@ class ManagedStdio(ManagedLog): def rotate(fileobj, maxsave=9): + """ Rotate fileobj. """ name = fileobj.name mode = fileobj.mode maxsize = fileobj.maxsize @@ -157,6 +167,7 @@ def rotate(fileobj, maxsave=9): # assumes basename logfile is closed. def shiftlogs(basename, maxsave): + """ Shift logfiles. """ topname = "%s.%d" % (basename, maxsave) if os.path.isfile(topname): os.unlink(topname) @@ -175,9 +186,11 @@ def shiftlogs(basename, maxsave): def open(name, maxsize=360000, maxsave=9): + """ Open logfile. """ return ManagedLog(name, maxsize, maxsave) def writelog(logobj, data): + """ Write logfile. """ try: logobj.write(data) except SizeError: diff --git a/wicd/misc.py b/wicd/misc.py index 046b7ad..af71f26 100644 --- a/wicd/misc.py +++ b/wicd/misc.py @@ -84,7 +84,8 @@ _sudo_dict = { _status_dict = { 'aborted': _('Connection Cancelled'), - 'association_failed': _('Connection failed: Could not contact the wireless access point.'), + 'association_failed': _('Connection failed: Could not contact the ' + \ + 'wireless access point.'), 'bad_pass': _('Connection Failed: Bad password'), 'configuring_interface': _('Configuring wireless interface...'), 'dhcp_failed': _('Connection Failed: Unable to Get IP Address'), @@ -107,6 +108,7 @@ _status_dict = { } class WicdError(Exception): + """ Custom Exception type. """ pass @@ -179,7 +181,8 @@ def LaunchAndWait(cmd): def IsValidIP(ip): """ Make sure an entered IP is valid. """ - if not ip: return False + if not ip: + return False if not IsValidIPv4(ip): if not IsValidIPv6(ip): @@ -218,9 +221,9 @@ def PromptToStartDaemon(): os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ) return True -def RunRegex(regex, string): +def RunRegex(regex, s): """ runs a regex search on a string """ - m = regex.search(string) + m = regex.search(s) if m: return m.groups()[0] else: @@ -271,12 +274,13 @@ def to_bool(var): var = bool(var) return var -def Noneify(variable, to_bool=True): +def Noneify(variable, convert_to_bool=True): """ Convert string types to either None or booleans""" #set string Nones to real Nones if variable in ("None", "", None): return None - if to_bool: + if convert_to_bool: + # FIXME: should instead use above to_bool()? if variable in ("False", "0"): return False if variable in ("True", "1"): @@ -415,8 +419,10 @@ def _parse_enc_template(enctype): print "Invalid 'optional' line found in template %s" % enctype continue elif line.startswith("protected"): - cur_type["protected"] = __parse_field_ent(parse_ent(line, "protected"), - field_type="protected") + cur_type["protected"] = __parse_field_ent( + parse_ent(line, "protected"), + field_type="protected" + ) if not cur_type["protected"]: # An error occured parsing the protected line. print "Invalid 'protected' line found in template %s" % enctype @@ -530,7 +536,8 @@ def detect_desktop_environment(): def get_sudo_cmd(msg, prog_num=0): """ Returns a graphical sudo command for generic use. """ sudo_prog = choose_sudo_prog(prog_num) - if not sudo_prog: return None + if not sudo_prog: + return None if re.search("(ktsuss|gksu|gksudo)$", sudo_prog): msg_flag = "-m" else: @@ -590,6 +597,8 @@ def stringToNone(text): return str(text) def checkboxTextboxToggle(checkbox, textboxes): + """ Manage {de,}activation of textboxes depending on checkboxes. """ + # FIXME: should be moved to UI-specific files? for textbox in textboxes: textbox.set_sensitive(checkbox.get_active()) @@ -613,7 +622,8 @@ def timeout_add(time, func, milli=False): if hasattr(gobject, "timeout_add_seconds") and not milli: return gobject.timeout_add_seconds(time, func) else: - if not milli: time = time * 1000 + if not milli: + time = time * 1000 return gobject.timeout_add(time, func) def izip_longest(*args, **kwds): diff --git a/wicd/monitor.py b/wicd/monitor.py index 86790c6..af573eb 100755 --- a/wicd/monitor.py +++ b/wicd/monitor.py @@ -47,6 +47,9 @@ wireless = dbus_dict["wireless"] mainloop = None def diewithdbus(func): + """ + Decorator catching DBus exceptions, making wicd quit. + """ def wrapper(self, *__args, **__kargs): try: ret = func(self, *__args, **__kargs) @@ -86,6 +89,7 @@ class ConnectionStatus(object): self.trigger_reconnect = False self.__lost_dbus_count = 0 self._to_time = daemon.GetBackendUpdateInterval() + self.update_callback = None self.add_poll_callback() bus = dbusmanager.get_bus() @@ -275,14 +279,14 @@ class ConnectionStatus(object): info = ["wired"] else: info = ["wireless", - misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))] + misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))] elif state == misc.WIRELESS: self.reconnect_tries = 0 info = [str(wifi_ip), - misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)), - str(self._get_printable_sig_strength()), - str(wireless.GetCurrentNetworkID(iwconfig)), - misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))] + misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)), + str(self._get_printable_sig_strength()), + str(wireless.GetCurrentNetworkID(iwconfig)), + misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))] elif state == misc.WIRED: self.reconnect_tries = 0 info = [str(wired_ip)] @@ -310,16 +314,18 @@ class ConnectionStatus(object): """ Get the correct signal strength format. """ try: if daemon.GetSignalDisplayType() == 0: - wifi_signal = int(wireless.GetCurrentSignalStrength(self.iwconfig)) + signal = wireless.GetCurrentSignalStrength(self.iwconfig) + wifi_signal = int(signal) else: + signal = wireless.GetCurrentDBMStrength(self.iwconfig) if always_positive: - # because dBm is negative, add 99 to the signal. This way, if - # the signal drops below -99, wifi_signal will == 0, and + # because dBm is negative, add 99 to the signal. This way, + # if the signal drops below -99, wifi_signal will == 0, and # an automatic reconnect will be triggered # this is only used in check_for_wireless_connection - wifi_signal = 99 + int(wireless.GetCurrentDBMStrength(self.iwconfig)) + wifi_signal = 99 + int(signal) else: - wifi_signal = int(wireless.GetCurrentDBMStrength(self.iwconfig)) + wifi_signal = int(signal) except TypeError: wifi_signal = 0 diff --git a/wicd/networking.py b/wicd/networking.py index a431886..0d6535a 100644 --- a/wicd/networking.py +++ b/wicd/networking.py @@ -158,25 +158,34 @@ class Controller(object): self.driver = None self.iface = None - def get_debug(self): return self._debug + def get_debug(self): + """ Getter for debug property. """ + return self._debug def set_debug(self, value): + """ Setter for debug property. """ self._debug = value if self.iface: self.iface.SetDebugMode(value) debug = property(get_debug, set_debug) def set_dhcp_client(self, value): + """ Setter for dhcp_client property. """ self._dhcp_client = value if self.iface: self.iface.DHCP_CLIENT = value - def get_dhcp_client(self): return self._dhcp_client + def get_dhcp_client(self): + """ Getter for dhcp_client property. """ + return self._dhcp_client dhcp_client = property(get_dhcp_client, set_dhcp_client) def set_flush_tool(self, value): + """ Setter for flush_tool property. """ self._flush_tool = value if self.iface: self.iface.flush_tool = value - def get_flush_tool(self): return self._flush_tool + def get_flush_tool(self): + """ Getter for flush_tool property. """ + return self._flush_tool flush_tool = property(get_flush_tool, set_flush_tool) def LoadBackend(self, backend_name): @@ -336,7 +345,10 @@ class ConnectThread(threading.Thread): self.debug = debug self.SetStatus('interface_down') - + + def _connect(self): + raise NotImplementedError + def run(self): self.connect_result = "failed" try: @@ -345,12 +357,15 @@ class ConnectThread(threading.Thread): self.is_connecting = False def set_should_die(self, val): + """ Setter for should_die property. """ self.lock.acquire() try: self._should_die = val finally: self.lock.release() - def get_should_die(self): return self._should_die + def get_should_die(self): + """ Getter for should_die property. """ + return self._should_die should_die = property(get_should_die, set_should_die) def SetStatus(self, status): @@ -401,6 +416,7 @@ class ConnectThread(threading.Thread): @abortable def run_global_scripts_if_needed(self, script_dir, extra_parameters=()): + """ Run global scripts if needed. '""" misc.ExecuteScripts(script_dir, verbose=self.debug, extra_parameters=extra_parameters) @@ -458,7 +474,7 @@ class ConnectThread(threading.Thread): hname = os.uname()[1] else: hname = self.network['dhcphostname'] - print "Running DHCP with hostname",hname + print "Running DHCP with hostname", hname dhcp_status = iface.StartDHCP(hname) if dhcp_status in ['no_dhcp_offers', 'dhcp_failed']: if self.connect_result != "aborted": @@ -564,22 +580,30 @@ class Wireless(Controller): self.should_verify_ap = True def set_wireless_iface(self, value): + """ Setter for wireless_interface property. """ self._wireless_interface = value if self.wiface: self.wiface.SetInterface(value) - def get_wireless_iface(self): return self._wireless_interface + def get_wireless_iface(self): + """ Getter for wireless_interface property. """ + return self._wireless_interface wireless_interface = property(get_wireless_iface, set_wireless_iface) def set_wpa_driver(self, value): + """ Setter for wpa_driver property. """ self._wpa_driver = value if self.wiface: self.SetWPADriver(value) - def get_wpa_driver(self): return self._wpa_driver + def get_wpa_driver(self): + """ Getter for wpa_driver property. """ + return self._wpa_driver wpa_driver = property(get_wpa_driver, set_wpa_driver) def set_iface(self, value): + """ Setter for iface property. """ self.wiface = value def get_iface(self): + """ Getter for iface property. """ return self.wiface iface = property(get_iface, set_iface) @@ -591,8 +615,9 @@ class Wireless(Controller): """ Controller.LoadBackend(self, backend) - if self._backend: - self.wiface = self._backend.WirelessInterface(self.wireless_interface, + backend = self._backend + if backend: + self.wiface = backend.WirelessInterface(self.wireless_interface, self.debug, self.wpa_driver) def Scan(self, essid=None): @@ -606,13 +631,15 @@ class Wireless(Controller): """ def comp(x, y): + """ Custom sorting function. """ if 'quality' in x: key = 'quality' else: key = 'strength' return cmp(x[key], y[key]) - if not self.wiface: return [] + if not self.wiface: + return [] wiface = self.wiface # Prepare the interface for scanning @@ -639,7 +666,8 @@ class Wireless(Controller): network -- network to connect to """ - if not self.wiface: return False + if not self.wiface: + return False self.connecting_thread = WirelessConnectThread(network, self.wireless_interface, self.wpa_driver, self.before_script, @@ -739,6 +767,7 @@ class Wireless(Controller): return BACKEND.GetWpaSupplicantDrivers() def StopWPA(self): + """ Stop wpa_supplicant. """ return self.wiface.StopWPA() def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, @@ -821,7 +850,8 @@ class Wireless(Controller): """ cmd = 'rfkill list' rfkill_out = misc.Run(cmd) - soft_blocks = filter(lambda x: x.startswith('Soft'), rfkill_out.split('\t')) + soft_blocks = filter(lambda x: x.startswith('Soft'), + rfkill_out.split('\t')) for line in map(lambda x: x.strip(), soft_blocks): if line.endswith('yes'): return True @@ -1015,7 +1045,8 @@ class WirelessConnectThread(ConnectThread): # cards). if self.debug: print "enctype is %s" % self.network.get('enctype') - if self.network.get('key') and 'wpa' in str(self.network.get('enctype')): + if self.network.get('key') and \ + 'wpa' in str(self.network.get('enctype')): self.SetStatus('generating_psk') print 'Generating psk...' self.network['psk'] = wiface.GeneratePSK(self.network) @@ -1044,23 +1075,31 @@ class Wired(Controller): self.liface = None def set_link_detect(self, value): + """ Setter for link_detect property. """ self._link_detect = value if self.liface: self.liface.link_detect = value - def get_link_detect(self): return self._link_detect + def get_link_detect(self): + """ Getter for link_detect property. """ + return self._link_detect link_detect = property(get_link_detect, set_link_detect) def set_wired_iface(self, value): + """ Setter for wired_interface property. """ self._wired_interface = value if self.liface: self.liface.SetInterface(value) - def get_wired_iface(self): return self._wired_interface + def get_wired_iface(self): + """ Getter for wired_interface property. """ + return self._wired_interface wired_interface = property(get_wired_iface, set_wired_iface) def set_iface(self, value): + """ Setter for iface property. """ self.liface = value def get_iface(self): + """ Getter for iface property. """ return self.liface iface = property(get_iface, set_iface) @@ -1087,7 +1126,8 @@ class Wired(Controller): network -- network to connect to """ - if not self.liface: return False + if not self.liface: + return False self.connecting_thread = WiredConnectThread(network, self.wired_interface, self.before_script, self.after_script, self.pre_disconnect_script, self.post_disconnect_script, @@ -1103,6 +1143,7 @@ class Wired(Controller): self.StopWPA() def StopWPA(self): + """ Stop wpa_supplicant. """ self.liface.StopWPA() def DetectWiredInterface(self): @@ -1165,9 +1206,9 @@ class WiredConnectThread(ConnectThread): # Run pre-connection script. self.run_global_scripts_if_needed(wpath.preconnectscripts, extra_parameters=('wired', 'wired', - self.network['profilename']) + self.network['profilename']) ) - self.run_script_if_needed(self.before_script, 'pre-connection', 'wired', + self.run_script_if_needed(self.before_script, 'pre-connection', 'wired', 'wired') # Take down interface and clean up previous connections. @@ -1195,7 +1236,7 @@ class WiredConnectThread(ConnectThread): extra_parameters=('wired', 'wired', self.network['profilename']) ) - self.run_script_if_needed(self.after_script, 'post-connection', 'wired', + self.run_script_if_needed(self.after_script, 'post-connection', 'wired', 'wired') self.SetStatus('done') diff --git a/wicd/suspend.py b/wicd/suspend.py index db19ac1..675a354 100755 --- a/wicd/suspend.py +++ b/wicd/suspend.py @@ -33,10 +33,9 @@ try: proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') except Exception, e: - print>>sys.stderr, "Exception caught: %s" % str(e) - print>>sys.stderr, 'Could not connect to daemon.' + print >> sys.stderr, "Exception caught: %s" % str(e) + print >> sys.stderr, 'Could not connect to daemon.' sys.exit(1) - if __name__ == '__main__': @@ -45,7 +44,6 @@ if __name__ == '__main__': daemon.SetForcedDisconnect(False) daemon.SetSuspend(True) except Exception, e: - print>>sys.stderr, "Exception caught: %s" % str(e) - print>>sys.stderr, 'Error setting suspend.' + print >> sys.stderr, "Exception caught: %s" % str(e) + print >> sys.stderr, 'Error setting suspend.' sys.exit(2) - diff --git a/wicd/translations.py b/wicd/translations.py index 3e7a052..0ae08dc 100644 --- a/wicd/translations.py +++ b/wicd/translations.py @@ -52,8 +52,7 @@ def get_gettext(): langs += ["en_US"] lang = gettext.translation('wicd', local_path, languages=langs, fallback=True) - _ = lang.ugettext - return _ + return lang.ugettext _ = get_gettext() @@ -67,13 +66,17 @@ language = {} # FIXME: these were present in wicd 1.7.0, can't find where they are. # Leaving here for future reference, they should be removed whenever # possible. -#language['cannot_start_daemon'] = _('''Unable to connect to wicd daemon DBus interface. This typically means there was a problem starting the daemon. Check the wicd log for more information.''') -#language['backend_alert'] = _('''Changes to your backend won't occur until the daemon is restarted.''') -#language['about_help'] = _('''Stop a network connection in progress''') -#language['connect'] = _('''Connect''') +#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \ +# 'DBus interface. This typically means there was a problem starting ' + \ +# 'the daemon. Check the wicd log for more information.') +#language['backend_alert'] = _('Changes to your backend won't occur until ' + \ +# 'the daemon is restarted.') +#language['about_help'] = _('Stop a network connection in progress') +#language['connect'] = _('Connect') # from templates, dict populated with: -# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | sed -e "s/*//"| sort -u | tr [A-Z] [a-z] +# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \ +# sed -e "s/*//" | sort -u | tr [A-Z] [a-z] language['authentication'] = _('Authentication') language['domain'] = _('Domain') language['identity'] = _('Identity') diff --git a/wicd/wicd-daemon.py b/wicd/wicd-daemon.py index 28171da..10b2a79 100644 --- a/wicd/wicd-daemon.py +++ b/wicd/wicd-daemon.py @@ -71,7 +71,7 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf") wired_conf = os.path.join(wpath.etc, "wired-settings.conf") dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template") -class WicdDaemon(dbus.service.Object): +class WicdDaemon(dbus.service.Object, object): """ The main wicd daemon class. This class mostly contains exported DBus methods that are not @@ -107,6 +107,17 @@ class WicdDaemon(dbus.service.Object): self.link_detect_tool = 0 self.flush_tool = 0 self.sudo_app = 0 + self.use_global_dns = False + self.always_show_wired_interface = True + self.wired_connect_mode = 1 + self.wired_bus.connect_mode = 1 + self.dns_dom = None + self.signal_display_type = 0 + self.dns1 = None + self.dns2 = None + self.dns3 = None + self.search_dom = None + self.auto_reconnect = True # This will speed up the scanning process - if a client doesn't # need a fresh scan, just feed them the old one. A fresh scan @@ -126,8 +137,10 @@ class WicdDaemon(dbus.service.Object): self.wireless_bus.Scan() def get_debug_mode(self): + """ Getter for debug_mode property. """ return self._debug_mode def set_debug_mode(self, mode): + """ Setter for debug_mode property. """ self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @@ -192,11 +205,13 @@ class WicdDaemon(dbus.service.Object): self.dns3 = dns3 self.wifi.global_dns_3 = dns3 self.wired.global_dns_3 = dns3 - self.config.set("Settings", "global_dns_dom", misc.noneToString(dns_dom)) + self.config.set("Settings", "global_dns_dom", + misc.noneToString(dns_dom)) self.dns_dom = dns_dom self.wifi.dns_dom = dns_dom self.wired.dns_dom = dns_dom - self.config.set("Settings", "global_search_dom", misc.noneToString(search_dom)) + self.config.set("Settings", "global_search_dom", + misc.noneToString(search_dom)) self.search_dom = search_dom self.wifi.global_search_dom = search_dom self.wired.global_search_dom = search_dom @@ -211,7 +226,8 @@ class WicdDaemon(dbus.service.Object): print "setting backend to %s" % backend backends = networking.BACKEND_MGR.get_available_backends() if backend not in backends: - print "backend %s not available, trying to fallback to another" % backend + print "backend %s not available, trying to fallback to another" \ + % backend try: backend = backends[0] except IndexError: @@ -310,18 +326,18 @@ class WicdDaemon(dbus.service.Object): self.wired.Disconnect() @dbus.service.method('org.wicd.daemon') - def FormatSignalForPrinting(self, signal): + def FormatSignalForPrinting(self, sign): """ Returns the suffix to display after the signal strength number. """ if self.GetSignalDisplayType() == 1: - return '%s dBm' % signal + return '%s dBm' % sign else: try: - if int(signal) == 101: + if int(sign) == 101: return '??%' else: - return '%s%%' % signal + return '%s%%' % sign except ValueError: - return '%s%%' % signal + return '%s%%' % sign @dbus.service.method('org.wicd.daemon') def SetSuspend(self, val): @@ -463,7 +479,8 @@ class WicdDaemon(dbus.service.Object): started. """ - if self.debug_mode and value: print "Forced disconnect on" + if self.debug_mode and value: + print "Forced disconnect on" self.forced_disconnect = bool(value) @dbus.service.method('org.wicd.daemon') @@ -578,7 +595,8 @@ class WicdDaemon(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def SetShowNeverConnect(self, value): """ Sets the how_never_connect state. """ - self.config.set("Settings", "show_never_connect", bool(value), write=True) + self.config.set("Settings", "show_never_connect", bool(value), + write=True) self.show_never_connect = bool(value) @dbus.service.method('org.wicd.daemon') @@ -746,7 +764,7 @@ class WicdDaemon(dbus.service.Object): try: gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect, fresh) - except: + except AttributeError: gobject.timeout_add(3000, self._monitor_wired_autoconnect, fresh) return True @@ -772,28 +790,36 @@ class WicdDaemon(dbus.service.Object): @dbus.service.method("org.wicd.daemon") def ConnectResultsAvailable(self): - if ((self.wired.connecting_thread and self.wired.connecting_thread.connect_result) or - (self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result)): + """ Return whether connection results are available. """ + wired_thread = self.wired.connecting_thread + wifi_thread = self.wifi.connecting_thread + if ((wired_thread and wired_thread.connect_result) or + (wifi_thread and wifi_thread.connect_result)): return True else: return False @dbus.service.method("org.wicd.daemon") def SendConnectResultsIfAvail(self): + """ Send connection results if they're available. '""" if self.ConnectResultsAvailable(): self.SendConnectResult() @dbus.service.method("org.wicd.daemon") def SendConnectResult(self): - if self.wired.connecting_thread and self.wired.connecting_thread.connect_result: - self.ConnectResultsSent(self.wired.connecting_thread.connect_result) - self.wired.connecting_thread.connect_result = "" - elif self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result: - self.ConnectResultsSent(self.wifi.connecting_thread.connect_result) - self.wifi.connecting_thread.connect_result = "" + """ Send connection result. """ + wired_thread = self.wired.connecting_thread + wifi_thread = self.wifi.connecting_thread + if wired_thread and wired_thread.connect_result: + self.ConnectResultsSent(wired_thread.connect_result) + wired_thread.connect_result = "" + elif wifi_thread and wifi_thread.connect_result: + self.ConnectResultsSent(wifi_thread.connect_result) + wifi_thread.connect_result = "" @dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s') def ConnectResultsSent(self, result): + """ Signal emit when connection results are sent. """ print "Sending connection attempt result %s" % result @dbus.service.method("org.wicd.daemon") @@ -853,25 +879,29 @@ class WicdDaemon(dbus.service.Object): # Load network interfaces. iface = self.wireless_bus.DetectWirelessInterface() - if not iface: iface = 'wlan0' + if not iface: + iface = 'wlan0' self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface", default=iface)) iface = self.wired_bus.DetectWiredInterface() - if not iface: iface = 'eth0' + if not iface: + iface = 'eth0' self.SetWiredInterface(app_conf.get("Settings", "wired_interface", default=iface)) - self.SetWPADriver(app_conf.get("Settings", "wpa_driver", default="wext")) + self.SetWPADriver(app_conf.get("Settings", "wpa_driver", + default="wext")) self.SetAlwaysShowWiredInterface(app_conf.get("Settings", - "always_show_wired_interface", - default=False)) + "always_show_wired_interface", + default=False)) self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns", default=False)) dns1 = app_conf.get("Settings", "global_dns_1", default='None') dns2 = app_conf.get("Settings", "global_dns_2", default='None') dns3 = app_conf.get("Settings", "global_dns_3", default='None') dns_dom = app_conf.get("Settings", "global_dns_dom", default='None') - search_dom = app_conf.get("Settings", "global_search_dom", default='None') + search_dom = app_conf.get("Settings", "global_search_dom", + default='None') self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom) self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect", default=True)) @@ -933,7 +963,7 @@ class WicdDaemon(dbus.service.Object): ###### Wireless Daemon ####### ############################## -class WirelessDaemon(dbus.service.Object): +class WirelessDaemon(dbus.service.Object, object): """ DBus interface for wireless connection operations. """ def __init__(self, bus_name, daemon, wifi=None, debug=False): """ Intitialize the wireless DBus interface. """ @@ -948,8 +978,10 @@ class WirelessDaemon(dbus.service.Object): self.config = ConfigManager(wireless_conf, debug=debug) def get_debug_mode(self): + """ Getter for the debug_mode property. """ return self._debug_mode def set_debug_mode(self, mode): + """ Setter for the debug_mode property. """ self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @@ -1068,10 +1100,10 @@ class WirelessDaemon(dbus.service.Object): return self.wifi.GetRfKillStatus() @dbus.service.method('org.wicd.daemon.wireless') - def GetWirelessProperty(self, networkid, property): + def GetWirelessProperty(self, networkid, prop): """ Retrieves wireless property from the network specified """ try: - value = self.LastScan[networkid].get(property) + value = self.LastScan[networkid].get(prop) except IndexError: return "" value = misc.to_unicode(value) @@ -1088,7 +1120,8 @@ class WirelessDaemon(dbus.service.Object): return False # whitelist some props that need different handling if prop in ('key_index', ): - self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value, False)) + self.LastScan[netid][prop] = \ + misc.to_unicode(misc.Noneify(value, False)) else: self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value)) @@ -1161,27 +1194,28 @@ class WirelessDaemon(dbus.service.Object): return result @dbus.service.method('org.wicd.daemon.wireless') - def ConnectWireless(self, id): + def ConnectWireless(self, nid): """ Connects the the wireless network specified by i""" - self.SaveWirelessNetworkProfile(id) + self.SaveWirelessNetworkProfile(nid) # Will returned instantly, that way we don't hold up dbus. # CheckIfWirelessConnecting can be used to test if the connection # is done. - self.wifi.before_script = self.GetWirelessProperty(id, 'beforescript') - self.wifi.after_script = self.GetWirelessProperty(id, 'afterscript') - self.wifi.pre_disconnect_script = self.GetWirelessProperty(id, - 'predisconnectscript') - self.wifi.post_disconnect_script = self.GetWirelessProperty(id, - 'postdisconnectscript') - self.wifi.bitrate = self.GetWirelessProperty(id, 'bitrate') - self.wifi.allow_lower_bitrates = self.GetWirelessProperty(id, - 'allow_lower_bitrates') - print 'Connecting to wireless network ' + str(self.LastScan[id]['essid']) + self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript') + self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript') + self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid, + 'predisconnectscript') + self.wifi.post_disconnect_script = self.GetWirelessProperty(nid, + 'postdisconnectscript') + self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate') + self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid, + 'allow_lower_bitrates') + print 'Connecting to wireless network ' + \ + str(self.LastScan[nid]['essid']) # disconnect to make sure that scripts are run self.wifi.Disconnect() self.daemon.wired_bus.wired.Disconnect() self.daemon.SetForcedDisconnect(False) - conthread = self.wifi.Connect(self.LastScan[id], debug=self.debug_mode) + self.wifi.Connect(self.LastScan[nid], debug=self.debug_mode) self.daemon.UpdateState() @dbus.service.method('org.wicd.daemon.wireless') @@ -1217,9 +1251,9 @@ class WirelessDaemon(dbus.service.Object): return False @dbus.service.method('org.wicd.daemon.wireless') - def ReadWirelessNetworkProfile(self, id): + def ReadWirelessNetworkProfile(self, nid): """ Reads in wireless profile as the active network """ - cur_network = self.LastScan[id] + cur_network = self.LastScan[nid] essid_key = "essid:%s" % cur_network["essid"] bssid_key = cur_network["bssid"] @@ -1247,13 +1281,13 @@ class WirelessDaemon(dbus.service.Object): cur_network['essid'] = stored_essid @dbus.service.method('org.wicd.daemon.wireless') - def SaveWirelessNetworkProfile(self, id): + def SaveWirelessNetworkProfile(self, nid): """ Writes a wireless profile to disk. """ def write_script_ent(prof, script): if not self.config.has_option(prof, script): self.config.set(prof, script, None) - cur_network = self.LastScan[id] + cur_network = self.LastScan[nid] bssid_key = cur_network["bssid"] essid_key = "essid:%s" % cur_network["essid"] @@ -1287,7 +1321,7 @@ class WirelessDaemon(dbus.service.Object): self.config.write() @dbus.service.method('org.wicd.daemon.wireless') - def SaveWirelessNetworkProperty(self, id, option): + def SaveWirelessNetworkProperty(self, nid, option): """ Writes a particular wireless property to disk. """ option = misc.sanitize_config(option) if option.endswith("script"): @@ -1295,7 +1329,7 @@ class WirelessDaemon(dbus.service.Object): 'the daemon.' return config = self.config - cur_network = self.LastScan[id] + cur_network = self.LastScan[nid] essid_key = "essid:" + cur_network["essid"] config.set(cur_network["bssid"], option, str(cur_network[option])) @@ -1347,12 +1381,14 @@ class WirelessDaemon(dbus.service.Object): self.config.remove_section(section) self.config.write() - @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='') + @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ + signature='') def SendStartScanSignal(self): """ Emits a signal announcing a scan has started. """ self._scanning = True - @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='') + @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ + signature='') def SendEndScanSignal(self): """ Emits a signal announcing a scan has finished. """ self._scanning = False @@ -1372,11 +1408,10 @@ class WirelessDaemon(dbus.service.Object): if self.debug_mode: print network["essid"] + ' has profile' if bool(network.get('automatic')): - try: - if network.get('never'): - print network["essid"],'marked never connect' - continue - except: + if network.get('never'): + print network["essid"],'marked never connect' + continue + else: print network["essid"],'has no never connect value' print 'trying to automatically connect to...' + \ network["essid"] @@ -1389,7 +1424,7 @@ class WirelessDaemon(dbus.service.Object): ###### Wired Daemon ####### ########################### -class WiredDaemon(dbus.service.Object): +class WiredDaemon(dbus.service.Object, object): """ DBus interface for wired connection operations. """ def __init__(self, bus_name, daemon, wired=None, debug=False): """ Intitialize the wireless DBus interface. """ @@ -1403,8 +1438,10 @@ class WiredDaemon(dbus.service.Object): self.config = ConfigManager(wired_conf, debug=debug) def get_debug_mode(self): + """ Getter for debug_mode property. """ return self._debug_mode def set_debug_mode(self, mode): + """ Setter for debug_mode property. """ self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @@ -1465,10 +1502,10 @@ class WiredDaemon(dbus.service.Object): return False @dbus.service.method('org.wicd.daemon.wired') - def GetWiredProperty(self, property): + def GetWiredProperty(self, prop): """ Returns the requested wired property. """ if self.WiredNetwork: - value = self.WiredNetwork.get(property) + value = self.WiredNetwork.get(prop) return value else: print 'GetWiredProperty: WiredNetwork does not exist' @@ -1516,8 +1553,10 @@ class WiredDaemon(dbus.service.Object): """ Connects to a wired network. """ self.wired.before_script = self.GetWiredProperty("beforescript") self.wired.after_script = self.GetWiredProperty("afterscript") - self.wired.pre_disconnect_script = self.GetWiredProperty("predisconnectscript") - self.wired.post_disconnect_script = self.GetWiredProperty("postdisconnectscript") + self.wired.pre_disconnect_script = \ + self.GetWiredProperty("predisconnectscript") + self.wired.post_disconnect_script = \ + self.GetWiredProperty("postdisconnectscript") self.daemon.wireless_bus.wifi.Disconnect() # make sure disconnect scripts are run self.wired.Disconnect() @@ -1537,13 +1576,13 @@ class WiredDaemon(dbus.service.Object): if self.config.has_section(profilename): return False - for option in ["ip", "broadcast", "netmask", "gateway", "search_domain", + for option in ["ip", "broadcast", "netmask", "gateway", "search_domain", "dns_domain", "dns1", "dns2", "dns3", "beforescript", "afterscript", "predisconnectscript", "postdisconnectscript", "encryption_enabled"]: self.config.set(profilename, option, None) self.config.set(profilename, "default", default) - self.config.set(profilename,"dhcphostname",os.uname()[1]) + self.config.set(profilename, "dhcphostname", os.uname()[1]) self.config.write() return True @@ -1628,7 +1667,8 @@ class WiredDaemon(dbus.service.Object): profile[x] = misc.Noneify(self.config.get(profilename, x)) profile['use_global_dns'] = bool(profile.get('use_global_dns')) profile['use_static_dns'] = bool(profile.get('use_static_dns')) - profile['encryption_enabled'] = bool(profile.get('encryption_enabled')) + profile['encryption_enabled'] = \ + bool(profile.get('encryption_enabled')) profile['profilename'] = profilename self.WiredNetwork = profile self._cur_wired_prof_name = profilename @@ -1657,6 +1697,7 @@ class WiredDaemon(dbus.service.Object): return wnettools.GetWiredInterfaces() def usage(): + """ Print help screen. """ print """ wicd %s wireless (and wired) connection daemon. @@ -1765,8 +1806,8 @@ def main(argv): try: opts, args = getopt.getopt(sys.argv[1:], 'fenoahk', - ['help', 'no-daemon', 'no-poll', 'no-stderr', 'no-stdout', - 'no-autoconnect', 'kill']) + ['help', 'no-daemon', 'no-poll', 'no-stderr', + 'no-stdout', 'no-autoconnect', 'kill']) except getopt.GetoptError: # Print help information and exit usage() @@ -1788,12 +1829,12 @@ def main(argv): if o in ('-n', '--no-poll'): no_poll = True if o in ('-k', '--kill'): - kill = True + kill = True if kill: try: f = open(wpath.pidfile) - except: + except IOError: #print >> sys.stderr, "No wicd instance active, aborting." sys.exit(1) @@ -1817,7 +1858,7 @@ def main(argv): dbus_ifaces['daemon'].Disconnect() pid = int(f.readline()) f.close() - os.kill(pid,signal.SIGTERM) + os.kill(pid, signal.SIGTERM) # quit, this should be the only option specified sys.exit(0) @@ -1830,7 +1871,8 @@ def main(argv): if not os.path.exists(wpath.networks): os.makedirs(wpath.networks) - if do_daemonize: daemonize() + if do_daemonize: + daemonize() if redirect_stderr or redirect_stdout: logpath = os.path.join(wpath.log, 'wicd.log') @@ -1840,8 +1882,8 @@ def main(argv): output = ManagedStdio(logpath) if os.path.exists(logpath): try: - os.chmod(logpath, int(wpath.log_perms,8)) - except: + os.chmod(logpath, int(wpath.log_perms, 8)) + except OSError: print 'unable to chmod log file to %s' % wpath.log_perms try: @@ -1849,11 +1891,13 @@ def main(argv): import grp group = grp.getgrnam(wpath.log_group) os.chown(logpath, 0, group[2]) - except: + except OSError: print 'unable to chown log file to %s' % group[2] - if redirect_stdout: sys.stdout = output - if redirect_stderr: sys.stderr = output + if redirect_stdout: + sys.stdout = output + if redirect_stderr: + sys.stderr = output print '---------------------------' print 'wicd initializing...' diff --git a/wicd/wnettools.py b/wicd/wnettools.py index d88831a..e38f7b8 100644 --- a/wicd/wnettools.py +++ b/wicd/wnettools.py @@ -49,7 +49,8 @@ essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode) ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode) channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode) strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode) -altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode) +altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', + _re_mode) signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode) bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode) mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode) @@ -61,12 +62,15 @@ wpa2_pattern = re.compile('(WPA2)', _re_mode) #iwconfig-only regular expressions. ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S) -ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S) +ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', + re.S) ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S) -bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: (([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode) +bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \ + '(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode) bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode) opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode) -authmethods_pattern = re.compile('.*Authentication capabilities :\n(.*?)Current', _re_mode) +authmethods_pattern = re.compile('.*Authentication capabilities ' + \ + ':\n(.*?)Current', _re_mode) # Regular expressions for wpa_cli output auth_pattern = re.compile('.*wpa_state=(.*?)\n', _re_mode) @@ -79,12 +83,14 @@ blacklist_norm = ";`$!*|><&\\" blank_trans = maketrans("", "") def _sanitize_string(string): + """ Sanitize string. """ if string: return translate(str(string), blank_trans, blacklist_norm) else: return string def _sanitize_string_strict(string): + """ Sanitize string in a stricter way. """ if string: return translate(str(string), blank_trans, blacklist_strict) else: @@ -140,7 +146,8 @@ def isWireless(devname): in the future, if wireless.h is fully replaced. """ we = None - for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25, socket.AF_APPLETALK]: + for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25, + socket.AF_APPLETALK]: sk = socket.socket(t, socket.SOCK_DGRAM) if sk is None: continue @@ -149,7 +156,7 @@ def isWireless(devname): #define SIOCGIWNAME 0x8b01 in linux/wireless.h # "used to verify the presence of wireless extensions" we = fcntl.ioctl(skfd, 0x8b01, devname) - except: + except IOError: pass sk.close() return we is not None @@ -184,7 +191,7 @@ def GetWpaSupplicantDrivers(): output = misc.Run(["wpa_supplicant", "-h"]) try: output = output.split("drivers:")[1].split("options:")[0].strip() - except: + except KeyError: print "Warning: Couldn't get list of valid wpa_supplicant drivers" return [""] patt = re.compile("(\S+)\s+=.*") @@ -236,7 +243,24 @@ class BaseInterface(object): self.flush_tool = None self.link_detect = None self.dhcp_object = None - + + self.ethtool_cmd = None + self.miitool_cmd = None + self.ip_cmd = None + self.route_cmd = None + self.wpa_cli_cmd = None + self.resolvconf_cmd = None + + self.dhclient_cmd = None + self.dhclient_needs_verbose = False + self.udhcpc_cmd = None + self.dhcpcd_cmd = None + self.pump_cmd = None + + self.kdesu_cmd = None + self.gksudo_cmd = None + self.ktsuss_cmd = None + def SetDebugMode(self, value): """ If True, verbose output is enabled. """ self.verbose = value @@ -363,7 +387,8 @@ class BaseInterface(object): "hostname" : hostname, 'dhclientconf' : dhclient_conf_path } elif flavor == "release": - return client_dict[client_name]['release'] % {"cmd":cmd, "iface":self.iface} + return client_dict[client_name]['release'] % \ + {"cmd": cmd, "iface": self.iface} else: return client_dict[client_name]['id'] @@ -429,6 +454,7 @@ class BaseInterface(object): self.route_cmd = self._find_program_path("route") def CheckSudoApplications(self): + """ Check for available root-gaining 'sudo' applications. """ self.gksudo_cmd = self._find_program_path("gksudo") self.kdesu_cmd = self._find_program_path("kdesu") self.ktsuss_cmd = self._find_program_path("ktsuss") @@ -442,7 +468,8 @@ class BaseInterface(object): """ cmd = 'ifconfig ' + self.iface + ' up' - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) return True @@ -455,7 +482,8 @@ class BaseInterface(object): """ cmd = 'ifconfig ' + self.iface + ' down' - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) return True @@ -464,7 +492,8 @@ class BaseInterface(object): def GetIfconfig(self): """ Runs ifconfig and returns the output. """ cmd = "ifconfig %s" % self.iface - if self.verbose: print cmd + if self.verbose: + print cmd return misc.Run(cmd) @neediface("") @@ -491,7 +520,8 @@ class BaseInterface(object): cmd = ''.join([cmd, 'netmask ', netmask, ' ']) if broadcast: cmd = ''.join([cmd, 'broadcast ', broadcast, ' ']) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) def _parse_dhclient(self, pipe): @@ -624,7 +654,8 @@ class BaseInterface(object): """ cmd = self._get_dhcp_command('connect', hostname) - if self.verbose: print cmd + if self.verbose: + print cmd self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True) pipe = self.dhcp_object.stdout client_dict = { misc.DHCLIENT : self._parse_dhclient, @@ -646,7 +677,8 @@ class BaseInterface(object): def ReleaseDHCP(self): """ Release the DHCP lease for this interface. """ cmd = self._get_dhcp_command("release") - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -659,7 +691,8 @@ class BaseInterface(object): else: print "No route manipulation command available!" return - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -671,7 +704,8 @@ class BaseInterface(object): """ if self.resolvconf_cmd: cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd'] - if self.verbose: print cmd + if self.verbose: + print cmd p = misc.Run(cmd, include_stderr=True, return_obj=True) p.communicate() @@ -711,7 +745,8 @@ class BaseInterface(object): if self.resolvconf_cmd: cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd'] - if self.verbose: print cmd + if self.verbose: + print cmd p = misc.Run(cmd, include_stderr=True, return_obj=True) p.communicate(input=resolv_params) else: @@ -730,7 +765,8 @@ class BaseInterface(object): print "No flush command available!" cmds = [] for cmd in cmds: - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -745,7 +781,8 @@ class BaseInterface(object): print 'WARNING: Invalid gateway found. Aborting!' return False cmd = 'route add default gw %s dev %s' % (gw, self.iface) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface("") @@ -763,7 +800,8 @@ class BaseInterface(object): # check multiple ifconfig output styles for pat in [ip_pattern, ip_pattern1]: m = misc.RunRegex(pat, output) - if m: return m + if m: + return m return None @neediface(False) @@ -784,7 +822,8 @@ class BaseInterface(object): # timeout, while the above will wait (-w) 3 seconds at # most. cmd = "ping -q -c 1 %s" % gateway - if self.verbose: print cmd + if self.verbose: + print cmd return misc.LaunchAndWait(cmd) @neediface(False) @@ -799,7 +838,8 @@ class BaseInterface(object): try: flags = open(flags_file, "r").read().strip() except IOError: - print "Could not open %s, using ifconfig to determine status" % flags_file + print "Could not open %s, using ifconfig to determine status" \ + % flags_file return self._slow_is_up(ifconfig) return bool(int(flags, 16) & 1) @@ -807,7 +847,8 @@ class BaseInterface(object): def StopWPA(self): """ Terminates wpa using wpa_cli""" cmd = 'wpa_cli -i %s terminate' % self.iface - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @@ -866,7 +907,8 @@ class BaseWiredInterface(BaseInterface): while True: tries += 1 time.sleep(2) - if self.IsUp() or tries > MAX_TRIES: break + if self.IsUp() or tries > MAX_TRIES: + break if os.path.exists(carrier_path): carrier = open(carrier_path, 'r') @@ -878,7 +920,8 @@ class BaseWiredInterface(BaseInterface): elif link == 0: return False except (IOError, ValueError, TypeError): - print 'Error checking link using /sys/class/net/%s/carrier' % self.iface + print 'Error checking link using /sys/class/net/%s/carrier' \ + % self.iface if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]: return self._eth_get_plugged_in() @@ -901,10 +944,13 @@ class BaseWiredInterface(BaseInterface): print 'Wired Interface is down, putting it up' self.Up() time.sleep(6) - if self.verbose: print cmd + if self.verbose: + print cmd tool_data = misc.Run(cmd, include_stderr=True) - if misc.RunRegex(re.compile('(Link detected: yes)', re.I | re.M | re.S), - tool_data): + if misc.RunRegex( + re.compile('(Link detected: yes)', re.I | re.M | re.S), + tool_data + ): return True else: return False @@ -917,14 +963,16 @@ class BaseWiredInterface(BaseInterface): """ cmd = "%s %s" % (self.miitool_cmd, self.iface) - if self.verbose: print cmd + if self.verbose: + print cmd tool_data = misc.Run(cmd, include_stderr=True) if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S), tool_data) is not None: print 'Wired Interface is down, putting it up' self.Up() time.sleep(4) - if self.verbose: print cmd + if self.verbose: + print cmd tool_data = misc.Run(cmd, include_stderr=True) if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S), @@ -934,11 +982,13 @@ class BaseWiredInterface(BaseInterface): return False def Authenticate(self, network): + """ Authenticate with wpa_supplicant. """ misc.ParseEncryption(network) cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c', os.path.join(wpath.networks, 'wired'), '-Dwired'] - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) class BaseWirelessInterface(BaseInterface): @@ -968,7 +1018,8 @@ class BaseWirelessInterface(BaseInterface): """ cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)] - if self.verbose: print str(cmd) + if self.verbose: + print str(cmd) misc.Run(cmd) @neediface(False) @@ -994,7 +1045,8 @@ class BaseWirelessInterface(BaseInterface): def GetIwconfig(self): """ Returns the output of iwconfig for this interface. """ cmd = "iwconfig " + self.iface - if self.verbose: print cmd + if self.verbose: + print cmd return misc.Run(cmd) def _FreqToChannel(self, freq): @@ -1019,7 +1071,7 @@ class BaseWirelessInterface(BaseInterface): try: ret = freq_dict[freq] except KeyError: - print "Couldn't determine channel number for frequency: " + str(freq) + print "Couldn't determine channel number for frequency:", str(freq) return ret @@ -1040,7 +1092,7 @@ class BaseWirelessInterface(BaseInterface): for x in lines: ap = {} info = x.split(" ") - info = filter(None, [x.strip() for x in info]) + info = [x.strip() for x in info if x.strip()] if len(info) < 5: continue if re.match(patt, info[2].upper()): @@ -1066,7 +1118,7 @@ class BaseWirelessInterface(BaseInterface): ap['enctype'] = info[4 + offset] elif info[5 + offset] == 'WPA2-PSK': ap['encryption_method'] = 'WPA2' - ap['authmode'] ="WPA2PSK" + ap['authmode'] = "WPA2PSK" ap['keyname'] = "WPA2PSK" ap['enctype'] = info[4 + offset] elif info[4 + offset] == "NONE": @@ -1075,7 +1127,8 @@ class BaseWirelessInterface(BaseInterface): print "Unknown AuthMode, can't assign encryption_method!" ap['encryption_method'] = 'Unknown' aps[bssid] = ap - if self.verbose: print str(aps) + if self.verbose: + print str(aps) return aps def _ParseRalinkAccessPoint(self, ap, ralink_info, cell): @@ -1090,7 +1143,6 @@ class BaseWirelessInterface(BaseInterface): Updated array containing info about the current access point """ - wep_pattern = re.compile('.*Encryption key:(.*?)\n', re.I | re.M | re.S) if ralink_info.has_key(ap['bssid']): info = ralink_info[ap['bssid']] for key in info.keys(): @@ -1115,7 +1167,8 @@ class BaseWirelessInterface(BaseInterface): if mode.lower() == 'master': mode = 'managed' cmd = 'iwconfig %s mode %s' % (self.iface, mode) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -1131,7 +1184,8 @@ class BaseWirelessInterface(BaseInterface): return False cmd = 'iwconfig %s channel %s' % (self.iface, str(channel)) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -1143,7 +1197,8 @@ class BaseWirelessInterface(BaseInterface): """ cmd = 'iwconfig %s key %s' % (self.iface, key) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) @neediface(False) @@ -1176,11 +1231,13 @@ class BaseWirelessInterface(BaseInterface): base = "iwconfig %s" % self.iface if channel and str(channel).isdigit(): cmd = "%s channel %s" % (base, str(channel)) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) if bssid: cmd = "%s ap %s" % (base, bssid) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) def GeneratePSK(self, network): @@ -1191,11 +1248,13 @@ class BaseWirelessInterface(BaseInterface): """ wpa_pass_path = misc.find_path('wpa_passphrase') - if not wpa_pass_path: return None + if not wpa_pass_path: + return None key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*', re.I | re.M | re.S) cmd = [wpa_pass_path, str(network['essid']), str(network['key'])] - if self.verbose: print cmd + if self.verbose: + print cmd return misc.RunRegex(key_pattern, misc.Run(cmd)) @neediface(False) @@ -1218,7 +1277,8 @@ class BaseWirelessInterface(BaseInterface): os.path.join(wpath.networks, network['bssid'].replace(':', '').lower()), driver] - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) def _AuthenticateRalinkLegacy(self, network): @@ -1243,7 +1303,8 @@ class BaseWirelessInterface(BaseInterface): print 'Setting up WEP' cmd = ''.join(['iwconfig ', self.iface, ' key ', network.get('key')]) - if self.verbose: print cmd + if self.verbose: + print cmd misc.Run(cmd) else: cmd_list = [] @@ -1251,13 +1312,14 @@ class BaseWirelessInterface(BaseInterface): cmd_list.append('AuthMode=' + info['authmode']) cmd_list.append('EncrypType=' + info['enctype']) cmd_list.append('SSID="%s"' % network['essid']) - cmd_list.append('%s="%s"' % (network['keyname'], network['key'])) + cmd_list.append('%(keyname)s="%(key)s"' % network) if info['nettype'] == 'SHARED' and info['enctype'] == 'WEP': cmd_list.append('DefaultKeyID=1') for cmd in cmd_list: cmd = ['iwpriv', self.iface, 'set', cmd] - if self.verbose: print ' '.join(cmd) + if self.verbose: + print ' '.join(cmd) misc.Run(cmd) @neediface([]) @@ -1269,7 +1331,8 @@ class BaseWirelessInterface(BaseInterface): """ cmd = 'iwlist ' + self.iface + ' scan' - if self.verbose: print cmd + if self.verbose: + print cmd results = misc.Run(cmd) # Split the networks apart, using Cell as our split point # this way we can look at only one network at a time. @@ -1501,7 +1564,8 @@ class BaseWirelessInterface(BaseInterface): """ Get the available authentication methods for the interface. """ if not iwlistauth: cmd = 'iwlist ' + self.iface + ' auth' - if self.verbose: print cmd + if self.verbose: + print cmd output = misc.Run(cmd) else: output = iwlistauth @@ -1515,13 +1579,14 @@ class BaseWirelessInterface(BaseInterface): """ Get the available bitrates the wifi card can use. """ cmd = 'iwlist ' + self.iface + ' rate' - if self.verbose: print cmd + if self.verbose: + print cmd rates = misc.Run(cmd) # process the output rates = rates.split('\n') - rates = filter(None, map(lambda x: x.strip().split(' ')[0], rates)) - rates = filter(lambda x: x[0].isdigit(), rates) + rates = [x.strip().split(' ')[0] for x in rates] + rates = [x for x in rates if x[0].isdigit()] return dbus.Array(rates, signature='v') def _get_link_quality(self, output):