diff --git a/.bzrignore b/.bzrignore index 9e12e8f..b76c2fe 100644 --- a/.bzrignore +++ b/.bzrignore @@ -28,3 +28,4 @@ wicd/wpath.py dist/ MANIFEST debian/ +.vscode/ diff --git a/cli/wicd-cli.py b/cli/wicd-cli.py index 8c260a6..54946af 100755 --- a/cli/wicd-cli.py +++ b/cli/wicd-cli.py @@ -52,13 +52,13 @@ try: '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() @@ -88,8 +88,8 @@ options, arguments = parser.parse_args() op_performed = False if not (options.wireless or options.wired) and not options.status: - print "Please use --wireless or --wired to specify " + \ - "the type of connection to operate on." + print("Please use --wireless or --wired to specify " + \ + "the type of connection to operate on.") if options.status: status, info = daemon.GetConnectionStatus() @@ -104,27 +104,27 @@ if options.status: connected = False status_msg = misc._const_status_dict[status] - print _('Connection status') + ': ' + status_msg + print(_('Connection status') + ': ' + status_msg) if connected: - print _('Connection type') + ': ' + conn_type + print(_('Connection type') + ': ' + conn_type) if status == misc.WIRELESS: strength = daemon.FormatSignalForPrinting(info[2]) - print _('Connected to $A at $B (IP: $C)') \ + print(_('Connected to $A at $B (IP: $C)') \ .replace('$A', info[1]) \ .replace('$B', strength) \ - .replace('$C', info[0]) - print _('Network ID: $A') \ - .replace('$A', info[3]) + .replace('$C', info[0])) + print(_('Network ID: $A') \ + .replace('$A', info[3])) else: - print _('Connected to wired network (IP: $A)') \ - .replace('$A', info[0]) + print(_('Connected to wired network (IP: $A)') \ + .replace('$A', info[0])) else: if status == misc.CONNECTING: if info[0] == 'wired': - print _('Connecting to wired network.') + print(_('Connecting to wired network.')) elif info[0] == 'wireless': - print _('Connecting to wireless network "$A".') \ - .replace('$A', info[1]) + print(_('Connecting to wireless network "$A".') \ + .replace('$A', info[1])) op_performed = True # functions @@ -132,7 +132,7 @@ 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.' + print('Invalid wireless network identifier.') sys.exit(1) def is_valid_wired_network_id(network_id): @@ -140,13 +140,13 @@ def is_valid_wired_network_id(network_id): num = len(wired.GetWiredProfileList()) if not (network_id < num and \ network_id >= 0): - print 'Invalid wired network identifier.' + print('Invalid wired network identifier.') 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.' + print('Profile of that name does not exist.') sys.exit(5) if options.scan and options.wireless: @@ -161,17 +161,17 @@ if options.load_profile and options.wired: if options.list_networks: if options.wireless: - print '#\tBSSID\t\t\tChannel\tESSID' + print('#\tBSSID\t\t\tChannel\tESSID') for network_id in range(0, wireless.GetNumberOfNetworks()): - print '%s\t%s\t%s\t%s' % (network_id, + print('%s\t%s\t%s\t%s' % (network_id, wireless.GetWirelessProperty(network_id, 'bssid'), wireless.GetWirelessProperty(network_id, 'channel'), - wireless.GetWirelessProperty(network_id, 'essid')) + wireless.GetWirelessProperty(network_id, 'essid'))) elif options.wired: - print '#\tProfile name' + print('#\tProfile name') i = 0 for profile in wired.GetWiredProfileList(): - print '%s\t%s' % (i, profile) + print('%s\t%s' % (i, profile)) i += 1 op_performed = True @@ -184,24 +184,24 @@ if options.network_details: network_id = wireless.GetCurrentNetworkID(0) is_valid_wireless_network_id(network_id) # we're connected to a network, print IP - print "IP: %s" % wireless.GetWirelessIP(0) + print("IP: %s" % wireless.GetWirelessIP(0)) - print "Essid: %s" % wireless.GetWirelessProperty(network_id, "essid") - print "Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid") + print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid")) + print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid")) if wireless.GetWirelessProperty(network_id, "encryption"): - print "Encryption: On" - print "Encryption Method: %s" % \ - wireless.GetWirelessProperty(network_id, "encryption_method") + print("Encryption: On") + print("Encryption Method: %s" % \ + 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("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")) op_performed = True # network properties @@ -216,14 +216,14 @@ 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) elif options.wired: if not options.set_to: - print wired.GetWiredProperty(options.network_property) + print(wired.GetWiredProperty(options.network_property)) else: wired.SetWiredProperty(options.network_property, options.set_to) op_performed = True @@ -232,13 +232,13 @@ if options.disconnect: daemon.Disconnect() if options.wireless: if wireless.GetCurrentNetworkID(0) > -1: - print "Disconnecting from %s on %s" % \ + print("Disconnecting from %s on %s" % \ (wireless.GetCurrentNetwork(0), - wireless.DetectWirelessInterface()) + 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: @@ -247,16 +247,16 @@ if options.connect: is_valid_wireless_network_id(options.network) name = wireless.GetWirelessProperty(options.network, 'essid') encryption = wireless.GetWirelessProperty(options.network, 'enctype') - print "Connecting to %s with %s on %s" % (name, encryption, - wireless.DetectWirelessInterface()) + print("Connecting to %s with %s on %s" % (name, encryption, + wireless.DetectWirelessInterface())) wireless.ConnectWireless(options.network) 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 = wired.CheckIfWiredConnecting @@ -277,10 +277,10 @@ if options.connect: # the loop check if next_ == "done": break - print message() + print(message()) last = next_ - print "done!" - if status() != u'done': + print("done!") + if status() != 'done': exit_status = 6 op_performed = True @@ -295,12 +295,12 @@ def str_properties(prop): if options.wireless and options.list_encryption_types: et = misc.LoadEncryptionMethods() # print 'Installed encryption templates:' - print '%s\t%-20s\t%s' % ('#', 'Name', 'Description') + print('%s\t%-20s\t%s' % ('#', 'Name', 'Description')) 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 '---' + 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']) i += 1 @@ -315,7 +315,7 @@ if options.save and options.network > -1: op_performed = True if not op_performed: - print "No operations performed." + print("No operations performed.") sys.exit(exit_status) diff --git a/curses/configscript_curses.py b/curses/configscript_curses.py index 29f6087..dc2aec2 100755 --- a/curses/configscript_curses.py +++ b/curses/configscript_curses.py @@ -45,7 +45,7 @@ def main(argv): """ Main function. """ global ui, frame if len(argv) < 2: - print 'Network id to configure is missing, aborting.' + print('Network id to configure is missing, aborting.') sys.exit(1) ui = urwid.curses_display.Screen() @@ -161,6 +161,6 @@ def run(): if __name__ == '__main__': if os.getuid() != 0: - print "Root privileges are required to configure scripts. Exiting." + print("Root privileges are required to configure scripts. Exiting.") sys.exit(0) main(sys.argv) diff --git a/curses/curses_misc.py b/curses/curses_misc.py index a8b94f7..1f69ce7 100644 --- a/curses/curses_misc.py +++ b/curses/curses_misc.py @@ -25,6 +25,7 @@ wicd-curses. import urwid from wicd.translations import _ +from functools import reduce # Uses code that is towards the bottom @@ -185,13 +186,12 @@ class MaskingEdit(urwid.Edit): """ Get masked out text. """ return self.mask_char * len(self.get_edit_text()) - def render(self, (maxcol, ), focus=False): + def render(self, xxx_todo_changeme, 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. + (maxcol, ) = xxx_todo_changeme if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus): # pylint: disable-msg=E1101 canv = self.__super.render((maxcol, ), focus) @@ -235,7 +235,7 @@ class TabColumns(urwid.WidgetWrap): 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(list(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]]) @@ -606,7 +606,7 @@ class Dialog2(urwid.WidgetWrap): raise DialogExit(-1) if k: self.unhandled_key(size, k) - except DialogExit, e: + except DialogExit as e: return self.on_exit(e.args[0]) def on_exit(self, exitcode): diff --git a/curses/netentry_curses.py b/curses/netentry_curses.py index 6df7731..75be530 100644 --- a/curses/netentry_curses.py +++ b/curses/netentry_curses.py @@ -402,7 +402,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): bool(wired.GetWiredProperty('usedhcphostname')) ) self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state()) - self.dhcp_h.set_edit_text(unicode(dhcphname)) + self.dhcp_h.set_edit_text(str(dhcphname)) def save_settings(self): """ Save settings to disk. """ @@ -415,7 +415,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): encrypt_methods[self.encryption_combo.get_focus()[1]]['type']) self.set_net_prop("encryption_enabled", True) # Make sure all required fields are filled in. - for entry_info in encrypt_info.itervalues(): + for entry_info in encrypt_info.values(): if entry_info[0].get_edit_text() == "" \ and entry_info[1] == 'required': error( @@ -428,7 +428,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): ) return False - for entry_key, entry_info in encrypt_info.iteritems(): + for entry_key, entry_info in encrypt_info.items(): self.set_net_prop(entry_key, noneToString(entry_info[0]. get_edit_text())) else: @@ -584,7 +584,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname')) ) self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state()) - self.dhcp_h.set_edit_text(unicode(dhcphname)) + self.dhcp_h.set_edit_text(str(dhcphname)) def set_net_prop(self, option, value): """ Sets the given option to the given value for this network. """ @@ -606,7 +606,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): encrypt_methods[self.encryption_combo.get_focus()[1]]['type'] ) # Make sure all required fields are filled in. - for entry_info in encrypt_info.itervalues(): + for entry_info in encrypt_info.values(): if entry_info[0].get_edit_text() == "" \ and entry_info[1] == 'required': error( @@ -619,7 +619,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): ) return False - for entry_key, entry_info in encrypt_info.iteritems(): + for entry_key, entry_info in encrypt_info.items(): self.set_net_prop(entry_key, noneToString(entry_info[0]. get_edit_text())) elif not self.encryption_chkbox.get_state() and \ diff --git a/curses/prefs_curses.py b/curses/prefs_curses.py index e04aaae..83d6d50 100644 --- a/curses/prefs_curses.py +++ b/curses/prefs_curses.py @@ -267,8 +267,8 @@ class PrefsDialog(urwid.WidgetWrap): """ Load settings to be used in the dialog. """ ### General Settings # ComboBox does not like dbus.Strings as text markups. My fault. :/ - wless_iface = unicode(daemon.GetWirelessInterface()) - wired_iface = unicode(daemon.GetWiredInterface()) + wless_iface = str(daemon.GetWirelessInterface()) + wired_iface = str(daemon.GetWiredInterface()) self.wless_edit.set_edit_text(wless_iface) self.wired_edit.set_edit_text(wired_iface) @@ -312,7 +312,7 @@ class PrefsDialog(urwid.WidgetWrap): self.wpadrivers.append("ralink_legacy") self.wpadrivers.append('none') # Same as above with the dbus.String - self.thedrivers = [unicode(w) for w in self.wpadrivers] + self.thedrivers = [str(w) for w in self.wpadrivers] self.wpa_cbox.set_list(self.thedrivers) # Pick where to begin first: @@ -323,7 +323,7 @@ class PrefsDialog(urwid.WidgetWrap): pass # It defaults to 0 anyway (I hope) self.backends = daemon.GetBackendList() - self.thebackends = [unicode(w) for w in self.backends] + self.thebackends = [str(w) for w in self.backends] self.backend_cbox.set_list(self.thebackends) cur_backend = daemon.GetSavedBackend() try: diff --git a/curses/wicd-curses.py b/curses/wicd-curses.py index 28649e5..5bf4cf4 100755 --- a/curses/wicd-curses.py +++ b/curses/wicd-curses.py @@ -99,15 +99,15 @@ def wrap_exceptions(func): #gobject.source_remove(redraw_tag) loop.quit() ui.stop() - print >> sys.stderr, "\n" + _('Terminated by user') + print("\n" + _('Terminated by user'), file=sys.stderr) #raise except DBusException: loop.quit() ui.stop() - print >> sys.stderr, "\n" + _('DBus failure! ' + print("\n" + _('DBus failure! ' 'This is most likely caused by the wicd daemon ' 'stopping while wicd-curses is running. ' - 'Please restart the daemon, and then restart wicd-curses.') + 'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr) raise except: # Quit the loop @@ -231,7 +231,7 @@ def help_dialog(body): textT = urwid.Text(('header', _('wicd-curses help')), 'right') textSH = urwid.Text([ 'This is ', ('blue', 'wicd-curses-' + CURSES_REV), - ' using wicd ', unicode(daemon.Hello()), '\n' + ' using wicd ', str(daemon.Hello()), '\n' ]) textH = urwid.Text([ @@ -517,7 +517,7 @@ class WiredComboBox(ComboBox): dialog = InputDialog( ('header', _('Rename wired profile')), 7, 30, - edit_text=unicode(self.get_selected_profile()) + edit_text=str(self.get_selected_profile()) ) exitcode, name = dialog.run(ui, self.parent) if exitcode == 0: @@ -1259,8 +1259,7 @@ def setup_dbus(force=True): try: dbusmanager.connect_to_dbus() except DBusException: - print >> sys.stderr, \ - _("Can't connect to the daemon, trying to start it automatically...") + print(_("Can't connect to the daemon, trying to start it automatically..."), file=sys.stderr) try: bus = dbusmanager.get_bus() @@ -1269,12 +1268,11 @@ def setup_dbus(force=True): wireless = dbus_ifaces['wireless'] wired = dbus_ifaces['wired'] except DBusException: - print >> sys.stderr, \ - _("Can't automatically start the daemon, this error is fatal...") + print(_("Can't automatically start the daemon, this error is fatal..."), file=sys.stderr) 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) netentry_curses.dbus_init(dbus_ifaces) @@ -1292,11 +1290,11 @@ if __name__ == '__main__': (CURSES_REV, daemon.Hello()), prog="wicd-curses" ) - except Exception, e: + except Exception as e: if "DBus.Error.AccessDenied" in e.get_dbus_name(): - print _('ERROR: wicd-curses was denied access to the wicd daemon: ' + print(_('ERROR: wicd-curses was denied access to the wicd daemon: ' 'please check that your user is in the "$A" group.'). \ - replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m') + replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')) sys.exit(1) else: raise diff --git a/gtk/configscript.py b/gtk/configscript.py index 0cdccfd..13e0e8b 100755 --- a/gtk/configscript.py +++ b/gtk/configscript.py @@ -120,7 +120,7 @@ def write_scripts(network, network_type, script_info): def main (argv): """ Runs the script configuration dialog. """ if len(argv) < 2: - print 'Network id to configure is missing, aborting.' + print('Network id to configure is missing, aborting.') sys.exit(1) network = argv[1] @@ -171,6 +171,6 @@ def main (argv): if __name__ == '__main__': if os.getuid() != 0: - print "Root privileges are required to configure scripts. Exiting." + print("Root privileges are required to configure scripts. Exiting.") sys.exit(0) main(sys.argv) diff --git a/gtk/gui.py b/gtk/gui.py index 1dcf723..3076ddc 100644 --- a/gtk/gui.py +++ b/gtk/gui.py @@ -56,11 +56,11 @@ def setup_dbus(force=True): dbusmanager.connect_to_dbus() except DBusException: if force: - print "Can't connect to the daemon, ' + \ - 'trying to start it automatically..." + print("Can't connect to the daemon, ' + \ + 'trying to start it automatically...") if not misc.PromptToStartDaemon(): - print "Failed to find a graphical sudo program, ' + \ - 'cannot continue." + print("Failed to find a graphical sudo program, ' + \ + 'cannot continue.") return False try: dbusmanager.connect_to_dbus() @@ -91,7 +91,7 @@ def handle_no_dbus(from_tray=False): DBUS_AVAIL = False if from_tray: return False - print "Wicd daemon is shutting down!" + print("Wicd daemon is shutting down!") error( None, _('The wicd daemon has shut down. The UI will not function ' @@ -146,14 +146,14 @@ class WiredProfileChooser: wired_net_entry.profile_help.hide() if wired_net_entry.profile_list is not None: wired_profiles.set_active(0) - print "wired profiles found" + print("wired profiles found") else: - print "no wired profiles found" + print("no wired profiles found") wired_net_entry.profile_help.show() response = dialog.run() if response == 1: - print 'reading profile ', wired_profiles.get_active_text() + print('reading profile ', wired_profiles.get_active_text()) wired.ReadWiredNetworkProfile(wired_profiles.get_active_text()) wired.ConnectWired() else: @@ -282,7 +282,7 @@ class appGui(object): def create_adhoc_network(self, widget=None): """ Shows a dialog that creates a new adhoc network. """ - print "Starting the Ad-Hoc Network Creation Process..." + print("Starting the Ad-Hoc Network Creation Process...") dialog = gtk.Dialog( title=_('Create an Ad-Hoc Network'), flags=gtk.DIALOG_MODAL, @@ -695,7 +695,7 @@ class appGui(object): wireless.SetHiddenNetworkESSID(noneToString(hidden)) self.refresh_clicked() return - print "refreshing..." + print("refreshing...") self.network_list.set_sensitive(False) self._remove_items_from_vbox(self.network_list) self.wait_for_events() @@ -707,7 +707,7 @@ class appGui(object): if num_networks > 0: skip_never_connect = not daemon.GetShowNeverConnect() instruct_label.show() - for x in xrange(0, num_networks): + for x in range(0, num_networks): if skip_never_connect and \ misc.to_bool(get_wireless_prop(x, 'never')): continue @@ -821,7 +821,7 @@ class appGui(object): # Make sure no entries are left blank if entry.chkbox_encryption.get_active(): encryption_info = entry.encryption_info - for entry_info in encryption_info.itervalues(): + for entry_info in encryption_info.values(): if entry_info[0].entry.get_text() == "" and \ entry_info[1] == 'required': error( diff --git a/gtk/guiutil.py b/gtk/guiutil.py index 797792a..0899971 100644 --- a/gtk/guiutil.py +++ b/gtk/guiutil.py @@ -25,16 +25,16 @@ HAS_NOTIFY = True try: import pynotify if not pynotify.init("Wicd"): - print 'Could not initalize pynotify' + print('Could not initalize pynotify') HAS_NOTIFY = False except ImportError: - print "Importing pynotify failed, notifications disabled." + print("Importing pynotify failed, notifications disabled.") HAS_NOTIFY = False -print "Has notifications support", HAS_NOTIFY +print("Has notifications support", HAS_NOTIFY) if wpath.no_use_notifications: - print 'Notifications disabled during setup.py configure' + print('Notifications disabled during setup.py configure') def can_use_notify(): diff --git a/gtk/netentry.py b/gtk/netentry.py index 5fd7988..28a8edd 100644 --- a/gtk/netentry.py +++ b/gtk/netentry.py @@ -465,14 +465,14 @@ class WiredSettingsDialog(AdvancedSettingsDialog): self.chkbox_encryption.get_active() ) if self.chkbox_encryption.get_active(): - print "setting encryption info..." + print("setting encryption info...") encrypt_methods = self.encrypt_types self.set_net_prop( "enctype", encrypt_methods[self.combo_encryption.get_active()]['type'] ) # Make sure all required fields are filled in. - for entry_info in encrypt_info.itervalues(): + for entry_info in encrypt_info.values(): if entry_info[0].entry.get_text() == "" and \ entry_info[1] == 'required': error( @@ -484,11 +484,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog): ) return False # Now save all the entries. - for entry_key, entry_info in encrypt_info.iteritems(): + for entry_key, entry_info in encrypt_info.items(): self.set_net_prop(entry_key, noneToString(entry_info[0].entry.get_text())) else: - print "no encryption specified..." + print("no encryption specified...") self.set_net_prop("enctype", "None") AdvancedSettingsDialog.save_settings(self) wired.SaveWiredNetworkProfile(self.prof_name) @@ -682,14 +682,14 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): # Check encryption info encrypt_info = self.encryption_info if self.chkbox_encryption.get_active(): - print "setting encryption info..." + print("setting encryption info...") encrypt_methods = self.encrypt_types self.set_net_prop( "enctype", encrypt_methods[self.combo_encryption.get_active()]['type'] ) # Make sure all required fields are filled in. - for entry_info in encrypt_info.itervalues(): + for entry_info in encrypt_info.values(): if entry_info[0].entry.get_text() == "" and \ entry_info[1] == 'required': error( @@ -701,7 +701,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): ) return False # Now save all the entries. - for entry_key, entry_info in encrypt_info.iteritems(): + for entry_key, entry_info in encrypt_info.items(): self.set_net_prop(entry_key, noneToString(entry_info[0].entry.get_text())) elif not self.chkbox_encryption.get_active() and \ @@ -710,7 +710,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): error(self, _('This network requires encryption to be enabled.')) return False else: - print "no encryption specified..." + print("no encryption specified...") self.set_net_prop("enctype", "None") AdvancedSettingsDialog.save_settings(self) @@ -861,7 +861,7 @@ class WiredNetworkEntry(NetworkEntry): starting_index = x self.combo_profile_names.set_active(starting_index) else: - print "no wired profiles found" + print("no wired profiles found") self.profile_help.show() self.advanced_dialog = \ @@ -942,7 +942,7 @@ class WiredNetworkEntry(NetworkEntry): def remove_profile(self, widget): """ Remove a profile from the profile list. """ - print "removing profile" + print("removing profile") profile_name = self.combo_profile_names.get_active_text() wired.DeleteWiredNetworkProfile(profile_name) self.combo_profile_names.remove_text(self.combo_profile_names. @@ -1010,7 +1010,7 @@ class WirelessNetworkEntry(NetworkEntry): self.lbl_encryption = GreyLabel() self.lbl_channel = GreyLabel() - print "ESSID : " + self.essid + print("ESSID : " + self.essid) self.chkbox_autoconnect = gtk.CheckButton( _('Automatically connect to this network')) self.chkbox_neverconnect = gtk.CheckButton( diff --git a/gtk/wicd-client.py b/gtk/wicd-client.py index 43c9bf7..044206a 100644 --- a/gtk/wicd-client.py +++ b/gtk/wicd-client.py @@ -80,8 +80,8 @@ if not hasattr(gtk, "StatusIcon"): import egg.trayicon USE_EGG = True except ImportError: - print 'Unable to load tray icon: Missing both egg.trayicon and ' + \ - 'gtk.StatusIcon modules.' + print('Unable to load tray icon: Missing both egg.trayicon and ' + \ + 'gtk.StatusIcon modules.') ICON_AVAIL = False misc.RenameProcess("wicd-client") @@ -101,7 +101,7 @@ def catchdbus(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) - except DBusException, e: + except DBusException as e: if e.get_dbus_name() is not None and \ "DBus.Error.AccessDenied" in e.get_dbus_name(): error( @@ -114,7 +114,7 @@ def catchdbus(func): #raise raise DBusException(e) else: - print "warning: ignoring exception %s" % e + print("warning: ignoring exception %s" % e) return None wrapper.__name__ = func.__name__ wrapper.__module__ = func.__module__ @@ -162,7 +162,7 @@ class TrayIcon(object): self.tr.toggle_wicd_gui() self.icon_info = self.TrayConnectionInfo(self, self.tr, animate) self.tr.icon_info = self.icon_info - print 'displaytray %s' % displaytray + print('displaytray %s' % displaytray) self.tr.visible(displaytray) def is_embedded(self): @@ -263,14 +263,14 @@ class TrayIcon(object): self._last_bubble.clear_hints() self._last_bubble.update(title, details, image) self._last_bubble.show() - except Exception, e: + except Exception as e: if hasattr(e, 'message') and e.message != '': msg = e.message elif hasattr(e, 'args') and len(e.args) > 0: msg = e.args[-1] else: msg = str(e) - print "Exception during notification: %s" % msg + print("Exception during notification: %s" % msg) self.should_notify = False @@ -386,7 +386,7 @@ class TrayIcon(object): elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): self.set_not_connected_state(info) else: - print 'Invalid state returned!!!' + print('Invalid state returned!!!') return False return True @@ -820,7 +820,7 @@ TX:''')) if num_networks > 0: skip_never_connect = not daemon.GetShowNeverConnect() - for x in xrange(0, num_networks): + for x in range(0, num_networks): if skip_never_connect and \ misc.to_bool(get_prop(x,"never")): continue @@ -1046,7 +1046,7 @@ TX:''')) def usage(): """ Print usage information. """ - print """ + print(""" wicd %s wireless (and wired) connection daemon front-end. @@ -1056,19 +1056,19 @@ Arguments: \t-h\t--help\t\tPrint this help information. \t-a\t--no-animate\tRun the tray without network traffic tray animations. \t-o\t--only-notifications\tDon't display anything except notifications. -""" % wpath.version +""" % wpath.version) def setup_dbus(force=True): """ Initialize DBus. """ global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id - print "Connecting to daemon..." + print("Connecting to daemon...") try: dbusmanager.connect_to_dbus() except DBusException: if force: - print "Can't connect to the daemon, trying to start it " + \ - "automatically..." + print("Can't connect to the daemon, trying to start it " + \ + "automatically...") misc.PromptToStartDaemon() try: dbusmanager.connect_to_dbus() @@ -1089,7 +1089,7 @@ def setup_dbus(force=True): wireless = dbus_ifaces['wireless'] wired = dbus_ifaces['wired'] DBUS_AVAIL = True - print "Connected." + print("Connected.") return True @@ -1107,7 +1107,7 @@ def handle_no_dbus(): global DBUS_AVAIL, lost_dbus_id DBUS_AVAIL = False gui.handle_no_dbus(from_tray=True) - print "Wicd daemon is shutting down!" + print("Wicd daemon is shutting down!") lost_dbus_id = misc.timeout_add(5, lambda: error(None, _('The wicd daemon has shut down. The UI will not function ' @@ -1151,14 +1151,14 @@ def main(argv): elif opt in ('-a', '--no-animate'): animate = False elif opt in ('-o', '--only-notifications'): - print "only displaying notifications" + print("only displaying notifications") use_tray = False display_app = False else: usage() sys.exit(2) - print 'Loading...' + print('Loading...') setup_dbus() atexit.register(on_exit) @@ -1195,7 +1195,7 @@ def main(argv): ) bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting", "org.wicd.daemon") - print 'Done loading.' + print('Done loading.') mainloop = gobject.MainLoop() mainloop.run() diff --git a/setup.py b/setup.py index 5c65986..654766f 100755 --- a/setup.py +++ b/setup.py @@ -51,9 +51,9 @@ try: pass import vcsinfo REVISION_NUM = vcsinfo.version_info['revno'] -except Exception, e: - print 'failed to find revision number:' - print e +except Exception as e: + print('failed to find revision number:') + print(e) class build(_build): sub_commands = _build.sub_commands + [('compile_translations', None)] @@ -216,10 +216,10 @@ class configure(Command): self.ddistro = 'FAIL' #self.no_install_init = True #self.distro_detect_failed = True - print 'WARNING: Unable to detect the distribution in use. ' + \ + print('WARNING: Unable to detect the distribution in use. ' + \ 'If you have specified --distro or --init and --initfile, configure will continue. ' + \ 'Please report this warning, along with the name of your ' + \ - 'distribution, to the wicd developers.' + 'distribution, to the wicd developers.') # Try to get the pm-utils sleep hooks directory from pkg-config and # the kde prefix from kde-config @@ -276,7 +276,7 @@ class configure(Command): self.logperms = '0600' def distro_check(self): - print "Distro is: " + self.distro + print("Distro is: " + self.distro) if self.distro in ['sles', 'suse']: self.init = '/etc/init.d/' self.initfile = 'init/suse/wicd' @@ -313,11 +313,11 @@ class configure(Command): self.initfile = 'init/lunar/wicd' else : if self.distro == 'auto': - print "NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that..." + print("NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that...") self.distro = self.ddistro self.distro_check() else: - print "WARNING: Distro detection failed!" + print("WARNING: Distro detection failed!") self.no_install_init = True self.distro_detect_failed = True @@ -326,8 +326,8 @@ class configure(Command): self.distro_check() if self.distro_detect_failed and not self.no_install_init and \ 'FAIL' in [self.init, self.initfile]: - print 'ERROR: Failed to detect distro. Configure cannot continue. ' + \ - 'Please specify --init and --initfile to continue with configuration.' + print('ERROR: Failed to detect distro. Configure cannot continue. ' + \ + 'Please specify --init and --initfile to continue with configuration.') # loop through the argument definitions in user_options for argument in self.user_options: @@ -353,26 +353,26 @@ class configure(Command): if argument[0].endswith('='): cur_arg = argument[0][:-1] cur_arg_value = getattr(self, cur_arg.replace('-', '_')) - print "%s is %s" % (cur_arg, cur_arg_value) + print("%s is %s" % (cur_arg, cur_arg_value)) values.append((cur_arg, getattr(self, cur_arg.replace('-','_')))) else: cur_arg = argument[0] cur_arg_value = getattr(self, cur_arg.replace('-', '_')) - print "Found switch %s %s" % (argument, cur_arg_value) + print("Found switch %s %s" % (argument, cur_arg_value)) values.append((cur_arg, bool(cur_arg_value))) - print 'Replacing values in template files...' + print('Replacing values in template files...') for item in os.listdir('in'): if item.endswith('.in'): - print 'Replacing values in',item, + print('Replacing values in',item, end=' ') original_name = os.path.join('in',item) item_in = open(original_name, 'r') final_name = item[:-3].replace('=','/') parent_dir = os.path.dirname(final_name) if parent_dir and not os.path.exists(parent_dir): - print '(mkdir %s)'%parent_dir, + print('(mkdir %s)'%parent_dir, end=' ') os.makedirs(parent_dir) - print final_name + print(final_name) item_out = open(final_name, 'w') for line in item_in.readlines(): for item, value in values: @@ -403,19 +403,19 @@ class clear_generated(Command): pass def run(self): - print 'Removing completed template files...' + print('Removing completed template files...') for item in os.listdir('in'): if item.endswith('.in'): - print 'Removing completed',item, + print('Removing completed',item, end=' ') original_name = os.path.join('in',item) final_name = item[:-3].replace('=','/') - print final_name, '...', + print(final_name, '...', end=' ') if os.path.exists(final_name): os.remove(final_name) - print 'Removed.' + print('Removed.') else: - print 'Does not exist.' - print 'Removing compiled translation files...' + print('Does not exist.') + print('Removing compiled translation files...') if os.path.exists('translations'): shutil.rmtree('translations/') os.makedirs('translations/') @@ -428,7 +428,7 @@ class install(_install): self.run_command('build') import wpath - print "Using init file",(wpath.init, wpath.initfile) + print("Using init file",(wpath.init, wpath.initfile)) data.extend([ (wpath.dbus, ['other/wicd.conf']), (wpath.dbus_service, ['other/org.wicd.daemon.service']), @@ -536,15 +536,15 @@ class install(_install): data.append((wpath.suspend, ['other/50-wicd-suspend.sh'])) if not wpath.no_install_pmutils: data.append((wpath.pmutils, ['other/55wicd'])) - print 'Using pid path', os.path.basename(wpath.pidfile) + print('Using pid path', os.path.basename(wpath.pidfile)) if not wpath.no_install_i18n: - print 'Language support for', + print('Language support for', end=' ') for language in sorted(glob('translations/*')): language = language.replace('translations/', '') - print language, + print(language, end=' ') data.append((wpath.translations + language + '/LC_MESSAGES/', ['translations/' + language + '/LC_MESSAGES/wicd.mo'])) - print + print() _install.run(self) @@ -560,9 +560,9 @@ class test(Command): pass def run(self): - print "importing tests" + print("importing tests") import tests - print 'running tests' + print('running tests') tests.run_tests() class update_message_catalog(Command): @@ -633,7 +633,7 @@ class compile_translations(Command): returncode = msgfmt.wait() # let it finish, and get the exit code output = msgfmt.stderr.readline().strip() if len(output) == 0 or returncode != 0: - print len(output), returncode + print(len(output), returncode) raise ValueError else: m = re.match('(\d+) translated messages(?:, (\d+) fuzzy translation)?(?:, (\d+) untranslated messages)?.', output) @@ -646,11 +646,11 @@ class compile_translations(Command): if completeness >= self.threshold: compile_po = True else: - print 'Disabled %s (%s%% < %s%%).' % \ - (lang, completeness*100, self.threshold*100) + print('Disabled %s (%s%% < %s%%).' % \ + (lang, completeness*100, self.threshold*100)) continue except (OSError, ValueError): - print 'ARGH' + print('ARGH') if compile_po: os.makedirs('translations/' + lang + '/LC_MESSAGES/') diff --git a/tests/__init__.py b/tests/__init__.py index 20af68e..c45be87 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -2,10 +2,10 @@ def run_tests(): import unittest test_suite = unittest.TestSuite() - import testwnettools + from . import testwnettools test_suite.addTest(testwnettools.suite()) - import testmisc + from . import testmisc test_suite.addTest(testmisc.suite()) unittest.TextTestRunner(verbosity=2).run(test_suite) diff --git a/tests/testmisc.py b/tests/testmisc.py index 189964e..77a6e16 100644 --- a/tests/testmisc.py +++ b/tests/testmisc.py @@ -7,7 +7,7 @@ from wicd import misc class TestMisc(unittest.TestCase): def test_misc_run(self): output = misc.Run(['echo', 'hi']).strip() - self.assertEquals('hi', output) + self.assertEqual('hi', output) def test_valid_ip_1(self): self.assertTrue(misc.IsValidIP('0.0.0.0')) @@ -55,13 +55,13 @@ class TestMisc(unittest.TestCase): import re regex = re.compile('.*(ABC.EFG).*') found = misc.RunRegex(regex, '01234ABCDEFG56789') - self.assertEquals(found, 'ABCDEFG') + self.assertEqual(found, 'ABCDEFG') def test_run_invalid_regex(self): import re regex = re.compile('.*(ABC.EFG).*') found = misc.RunRegex(regex, '01234ABCEDFG56789') - self.assertEquals(found, None) + self.assertEqual(found, None) def test_to_boolean_false(self): self.assertFalse(misc.to_bool('False')) @@ -76,13 +76,13 @@ class TestMisc(unittest.TestCase): self.assertTrue(misc.to_bool('1')) def test_noneify_1(self): - self.assertEquals(misc.Noneify('None'), None) + self.assertEqual(misc.Noneify('None'), None) def test_noneify_2(self): - self.assertEquals(misc.Noneify(''), None) + self.assertEqual(misc.Noneify(''), None) def test_noneify_3(self): - self.assertEquals(misc.Noneify(None), None) + self.assertEqual(misc.Noneify(None), None) def test_noneify_4(self): self.assertFalse(misc.Noneify('False')) @@ -103,65 +103,65 @@ class TestMisc(unittest.TestCase): self.assertTrue(misc.Noneify(True)) def test_noneify_10(self): - self.assertEquals(misc.Noneify('randomtext'), 'randomtext') + self.assertEqual(misc.Noneify('randomtext'), 'randomtext') def test_noneify_11(self): - self.assertEquals(misc.Noneify(5), 5) + self.assertEqual(misc.Noneify(5), 5) def test_noneify_12(self): - self.assertEquals(misc.Noneify(1, False), 1) + self.assertEqual(misc.Noneify(1, False), 1) def test_noneify_13(self): - self.assertEquals(misc.Noneify(0, False), 0) + self.assertEqual(misc.Noneify(0, False), 0) def test_none_to_string_1(self): - self.assertEquals(misc.noneToString(None), 'None') + self.assertEqual(misc.noneToString(None), 'None') def test_none_to_string_2(self): - self.assertEquals(misc.noneToString(''), 'None') + self.assertEqual(misc.noneToString(''), 'None') def test_none_to_string_3(self): - self.assertEquals(misc.noneToString(None), 'None') + self.assertEqual(misc.noneToString(None), 'None') #################################################################### # misc.to_unicode actually converts to utf-8, which is type str # #################################################################### def test_to_unicode_1(self): - self.assertEquals(misc.to_unicode('邪悪'), '邪悪') + self.assertEqual(misc.to_unicode('邪悪'), '邪悪') def test_to_unicode_2(self): - self.assertEquals(misc.to_unicode(u'邪悪'), '邪悪') + self.assertEqual(misc.to_unicode('邪悪'), '邪悪') def test_to_unicode_3(self): - self.assertEquals(misc.to_unicode(u'abcdef'), 'abcdef') + self.assertEqual(misc.to_unicode('abcdef'), 'abcdef') def test_to_unicode_4(self): - self.assertEquals(type(misc.to_unicode('abcdef'.encode('latin-1'))), str) + self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), str) def test_to_unicode_5(self): - self.assertEquals(misc.to_unicode("berkåk"), "berkåk") + self.assertEqual(misc.to_unicode("berkåk"), "berkåk") def test_to_unicode_6(self): - self.assertEquals(misc.to_unicode('berk\xe5k'), "berkåk") + self.assertEqual(misc.to_unicode('berk\xe5k'), "berkåk") def test_none_to_blank_string_1(self): - self.assertEquals(misc.noneToBlankString(None), '') + self.assertEqual(misc.noneToBlankString(None), '') def test_none_to_blank_string_2(self): - self.assertEquals(misc.noneToBlankString('None'), '') + self.assertEqual(misc.noneToBlankString('None'), '') def test_string_to_none_1(self): - self.assertEquals(misc.stringToNone(''), None) + self.assertEqual(misc.stringToNone(''), None) def test_string_to_none_2(self): - self.assertEquals(misc.stringToNone('None'), None) + self.assertEqual(misc.stringToNone('None'), None) def test_string_to_none_3(self): - self.assertEquals(misc.stringToNone(None), None) + self.assertEqual(misc.stringToNone(None), None) def test_string_to_none_4(self): - self.assertEquals(misc.stringToNone('abcdef'), 'abcdef') + self.assertEqual(misc.stringToNone('abcdef'), 'abcdef') def suite(): suite = unittest.TestSuite() diff --git a/tests/testwnettools.py b/tests/testwnettools.py index 0b1a718..dabef59 100644 --- a/tests/testwnettools.py +++ b/tests/testwnettools.py @@ -35,23 +35,23 @@ class TestWnettools(unittest.TestCase): def test_interface_name_sanitation(self): interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat') - self.assertEquals(interface.iface, 'blahblahuptimetmpblahcat') + self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat') def test_freq_translation_low(self): freq = '2.412 GHz' interface = wnettools.BaseWirelessInterface('wlan0') - self.assertEquals(interface._FreqToChannel(freq), 1) + self.assertEqual(interface._FreqToChannel(freq), 1) def test_freq_translation_high(self): freq = '2.484 GHz' interface = wnettools.BaseWirelessInterface('wlan0') - self.assertEquals(interface._FreqToChannel(freq), 14) + self.assertEqual(interface._FreqToChannel(freq), 14) def test_generate_psk(self): interface = wnettools.BaseWirelessInterface('wlan0') if 'wlan0' in wnettools.GetWirelessInterfaces(): psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'}) - self.assertEquals(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be') + self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be') def suite(): suite = unittest.TestSuite() diff --git a/wicd/autoconnect.py b/wicd/autoconnect.py index 7b1fe43..b2aba1f 100755 --- a/wicd/autoconnect.py +++ b/wicd/autoconnect.py @@ -35,9 +35,9 @@ try: dbusmanager.connect_to_dbus() 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.' +except Exception as e: + print("Exception caught: %s" % str(e), file=sys.stderr) + print('Could not connect to daemon.', file=sys.stderr) sys.exit(1) def handler(*args): @@ -45,7 +45,7 @@ def handler(*args): pass def error_handler(*args): """ Error handler. """ - print >> sys.stderr, 'Async error autoconnecting.' + print('Async error autoconnecting.', file=sys.stderr) sys.exit(3) if __name__ == '__main__': @@ -55,7 +55,7 @@ if __name__ == '__main__': if not daemon.CheckIfConnecting(): 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.' + except Exception as e: + print("Exception caught: %s" % str(e), file=sys.stderr) + print('Error autoconnecting.', file=sys.stderr) sys.exit(2) diff --git a/wicd/backend.py b/wicd/backend.py index bf4f220..d73d9dc 100644 --- a/wicd/backend.py +++ b/wicd/backend.py @@ -31,7 +31,7 @@ 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) + print("Failed to load backend %s: %s" % (backend_name, reason)) return True @@ -80,7 +80,7 @@ class BackendManager(object): def _load_backend(self, backend_name): """ Imports a backend and returns the loaded module. """ - print 'trying to load backend %s' % backend_name + print('trying to load backend %s' % backend_name) backend_path = os.path.join(self.backend_dir, 'be-' + backend_name + '.py') if self._valid_backend_file(backend_path): @@ -124,5 +124,5 @@ class BackendManager(object): return None self.__loaded_backend = backend - print 'successfully loaded backend %s' % backend_name + print('successfully loaded backend %s' % backend_name) return backend diff --git a/wicd/backends/be-ioctl.py b/wicd/backends/be-ioctl.py index ac3b2bb..9bcd540 100644 --- a/wicd/backends/be-ioctl.py +++ b/wicd/backends/be-ioctl.py @@ -41,13 +41,13 @@ try: import iwscan IWSCAN_AVAIL = True except ImportError: - print "WARNING: python-iwscan not found, falling back to using iwlist scan." + print("WARNING: python-iwscan not found, falling back to using iwlist scan.") IWSCAN_AVAIL = False try: import wpactrl WPACTRL_AVAIL = True except ImportError: - print "WARNING: python-wpactrl not found, falling back to using wpa_cli." + print("WARNING: python-wpactrl not found, falling back to using wpa_cli.") WPACTRL_AVAIL = False import re @@ -165,9 +165,9 @@ class Interface(BaseInterface): data = (self.iface + '\0' * 16)[:18] try: result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data) - except IOError, e: + except IOError as e: if self.verbose: - print "SIOCGIFFLAGS failed: " + str(e) + print("SIOCGIFFLAGS failed: " + str(e)) return False flags, = struct.unpack('H', result[16:18]) @@ -204,8 +204,8 @@ class WiredInterface(Interface, BaseWiredInterface): elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]: return self._mii_get_plugged_in() else: - print ('Error: No way of checking for a wired connection. Make' + - 'sure that either mii-tool or ethtool is installed.') + print(('Error: No way of checking for a wired connection. Make' + + 'sure that either mii-tool or ethtool is installed.')) return False def _eth_get_plugged_in(self): @@ -224,9 +224,9 @@ class WiredInterface(Interface, BaseWiredInterface): data = (self.iface + '\0' * 16)[:16] + arg try: fcntl.ioctl(self.sock.fileno(), SIOCETHTOOL, data) - except IOError, e: + except IOError as e: if self.verbose: - print 'SIOCETHTOOL failed: ' + str(e) + print('SIOCETHTOOL failed: ' + str(e)) return False return bool(buff.tolist()[1]) @@ -244,9 +244,9 @@ class WiredInterface(Interface, BaseWiredInterface): 0x0004, 0) try: result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff) - except IOError, e: + except IOError as e: if self.verbose: - print 'SIOCGMIIPHY failed: ' + str(e) + print('SIOCGMIIPHY failed: ' + str(e)) return False reg = struct.unpack('16shhhh', result)[-1] return bool(reg & 0x0004) @@ -286,16 +286,16 @@ class WirelessInterface(Interface, BaseWirelessInterface): if not self.scan_iface: try: self.scan_iface = iwscan.WirelessInterface(self.iface) - except iwscan.error, e: - print "GetNetworks caught an exception: %s" % e + except iwscan.error as e: + print("GetNetworks caught an exception: %s" % e) return [] try: results = self.scan_iface.Scan() - except iwscan.error, e: - print "ERROR: %s" % e + except iwscan.error as e: + print("ERROR: %s" % e) return [] - return filter(None, [self._parse_ap(cell) for cell in results]) + return [_f for _f in [self._parse_ap(cell) for cell in results] if _f] def _parse_ap(self, cell): """ Parse a single cell from the python-iwscan list. """ @@ -303,7 +303,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): try: ap['essid'] = misc.to_unicode(cell['essid']) except UnicodeError: - print 'Unicode problem with the current network essid, ignoring!!' + print('Unicode problem with the current network essid, ignoring!!') return None if ap['essid'] in [ "", '']: @@ -356,12 +356,12 @@ class WirelessInterface(Interface, BaseWirelessInterface): if os.path.exists(socket_loc): try: return wpactrl.WPACtrl(socket_loc) - except wpactrl.error, e: - print "Couldn't open ctrl_interface: %s" % e + except wpactrl.error as e: + 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): @@ -392,7 +392,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): wpa = self._connect_to_wpa_ctrl_iface() if not wpa: - print "Failed to open ctrl interface" + print("Failed to open ctrl interface") return False MAX_TIME = 35 @@ -402,12 +402,12 @@ class WirelessInterface(Interface, BaseWirelessInterface): try: status = wpa.request("STATUS").split("\n") except: - print "wpa_supplicant status query failed." + print("wpa_supplicant status query failed.") 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=")] @@ -426,7 +426,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): disconnected_time = 0 time.sleep(1) - print 'wpa_supplicant authentication may have failed.' + print('wpa_supplicant authentication may have failed.') return False @neediface(False) @@ -458,28 +458,28 @@ class WirelessInterface(Interface, BaseWirelessInterface): if info[2] == network.get('essid'): if info[5] == 'WEP' or (info[5] == 'OPEN' and \ info[4] == 'WEP'): - print 'Setting up WEP' + print('Setting up WEP') cmd = ''.join(['iwconfig ', self.iface, ' key ', network.get('key')]) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) else: if info[5] == 'SHARED' and info[4] == 'WEP': - print 'Setting up WEP' + print('Setting up WEP') auth_mode = 'SHARED' key_name = 'Key1' elif info[5] == 'WPA-PSK': - print 'Setting up WPA-PSK' + print('Setting up WPA-PSK') auth_mode = 'WPAPSK' key_name = 'WPAPSK' elif info[5] == 'WPA2-PSK': - print 'Setting up WPA2-PSK' + print('Setting up WPA2-PSK') auth_mode = 'WPA2PSK' key_name = 'WPAPSK' else: - print 'Unknown AuthMode, can\'t complete ' + \ - 'connection process!' + print('Unknown AuthMode, can\'t complete ' + \ + 'connection process!') return cmd_list = [] @@ -495,7 +495,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): for cmd in cmd_list: cmd = 'iwpriv ' + self.iface + ' ' if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface("") @@ -504,9 +504,9 @@ class WirelessInterface(Interface, BaseWirelessInterface): data = (self.iface + '\0' * 32)[:32] try: result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:] - except IOError, e: + except IOError as e: if self.verbose: - print "SIOCGIWAP failed: " + str(e) + print("SIOCGIWAP failed: " + str(e)) return "" raw_addr = struct.unpack("xxBBBBBB", result[:8]) return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr @@ -519,9 +519,9 @@ class WirelessInterface(Interface, BaseWirelessInterface): size = struct.calcsize(fmt) try: result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRATE, data)[16:] - except IOError, e: + except IOError as e: if self.verbose: - print "SIOCGIWRATE failed: " + str(e) + print("SIOCGIWRATE failed: " + str(e)) return "" f, e, x, x = struct.unpack(fmt, result[:size]) return "%s %s" % ((f / 1000000), 'Mb/s') @@ -562,9 +562,9 @@ class WirelessInterface(Interface, BaseWirelessInterface): iwfreq = (self.iface + '\0' * 16)[:16] + arg try: result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRANGE, iwfreq) - except IOError, e: + except IOError as e: if self.verbose: - print "SIOCGIWRANGE failed: " + str(e) + print("SIOCGIWRANGE failed: " + str(e)) return None # This defines the iwfreq struct, used to get signal strength. fmt = "iiihb6ii4B4Bi32i2i2i2i2i3h8h2b2bhi8i2b3h2i2ihB17x" + 32 * "ihbb" diff --git a/wicd/configmanager.py b/wicd/configmanager.py index d026170..f925b50 100644 --- a/wicd/configmanager.py +++ b/wicd/configmanager.py @@ -27,7 +27,7 @@ reusable for other purposes as well. import sys, os -from ConfigParser import RawConfigParser, ParsingError +from configparser import RawConfigParser, ParsingError import codecs from wicd.misc import Noneify, to_unicode @@ -61,8 +61,8 @@ class ConfigManager(RawConfigParser): self.write() try: self.read(path) - except ParsingError, p: - print "Could not start wicd: %s" % p.message + except ParsingError as p: + print("Could not start wicd: %s" % p.message) sys.exit(1) def __repr__(self): @@ -86,7 +86,7 @@ class ConfigManager(RawConfigParser): """ if not self.has_section(section): self.add_section(section) - if isinstance(value, basestring): + if isinstance(value, str): value = to_unicode(value) if value.startswith(' ') or value.endswith(' '): value = "%(ws)s%(value)s%(ws)s" % {"value" : value, @@ -115,7 +115,7 @@ class ConfigManager(RawConfigParser): if self.has_option(section, option): ret = RawConfigParser.get(self, section, option) - if (isinstance(ret, basestring) and ret.startswith(self.mrk_ws) + if (isinstance(ret, str) and ret.startswith(self.mrk_ws) and ret.endswith(self.mrk_ws)): ret = ret[3:-3] ret = to_unicode(ret) @@ -125,15 +125,15 @@ class ConfigManager(RawConfigParser): if option in ['apsk', 'password', 'identity', \ 'private_key', 'private_key_passwd', \ 'key', 'passphrase']: - print ''.join(['found ', option, \ - ' in configuration *****']) + print(''.join(['found ', option, \ + ' in configuration *****'])) else: - print ''.join(['found ', option, ' in configuration ', - str(ret)]) + print(''.join(['found ', option, ' in configuration ', + str(ret)])) else: # Use the default, unless no default was provided 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: @@ -146,7 +146,7 @@ class ConfigManager(RawConfigParser): except (ValueError, TypeError, AttributeError): ret = Noneify(ret) # This is a workaround for a python-dbus issue on 64-bit systems. - if isinstance(ret, (int, long)): + if isinstance(ret, int): try: Int32(ret) except OverflowError: diff --git a/wicd/misc.py b/wicd/misc.py index 508fef9..544e999 100644 --- a/wicd/misc.py +++ b/wicd/misc.py @@ -30,8 +30,8 @@ import string import gobject from threading import Thread from subprocess import Popen, STDOUT, PIPE, call -from commands import getoutput -from itertools import repeat, chain, izip +from subprocess import getoutput +from itertools import repeat, chain from pipes import quote import socket @@ -154,8 +154,8 @@ def Run(cmd, include_stderr=False, return_pipe=False, try: f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err, close_fds=fds, cwd='/', env=tmpenv) - except OSError, e: - print "Running command %s failed: %s" % (str(cmd), str(e)) + except OSError as e: + print("Running command %s failed: %s" % (str(cmd), str(e))) return "" if return_obj: @@ -252,10 +252,10 @@ def ExecuteScript(script, verbose=False, extra_parameters=()): # escape script name script = quote(script) if verbose: - print "Executing %s with params %s" % (script, params) + print("Executing %s with params %s" % (script, params)) ret = call('%s %s > /dev/null 2>&1' % (script, params), shell=True) if verbose: - print "%s returned %s" % (script, ret) + print("%s returned %s" % (script, ret)) def ReadFile(filename): """ read in a file and return it's contents as a string """ @@ -322,9 +322,9 @@ def ParseEncryption(network): if rep_val: line = line.replace("$_%s" % cur_val, str(rep_val)) else: - print "Ignoring template line: '%s'" % line + print("Ignoring template line: '%s'" % line) else: - print "Weird parsing error occurred" + print("Weird parsing error occurred") config_file = ''.join([config_file, line]) else: # Just a regular entry. config_file = ''.join([config_file, line]) @@ -337,7 +337,7 @@ def ParseEncryption(network): file_name = 'wired' file_loc = os.path.join(wpath.networks, file_name) f = open(file_loc, "w") - os.chmod(file_loc, 0600) + os.chmod(file_loc, 0o600) os.chown(file_loc, 0, 0) # We could do this above, but we'd like to read protect # them before we write, so that it can't be read. @@ -358,8 +358,8 @@ def LoadEncryptionMethods(wired = False): active_fname = "active" try: enctypes = open(wpath.encryption + active_fname,"r").readlines() - except IOError, e: - print "Fatal Error: template index file is missing." + except IOError as e: + print("Fatal Error: template index file is missing.") raise IOError(e) # Parse each encryption method @@ -391,7 +391,7 @@ def _parse_enc_template(enctype): try: f = open(os.path.join(wpath.encryption, enctype), "r") except IOError: - print "Failed to open template file %s" % enctype + print("Failed to open template file %s" % enctype) return None cur_type = {} @@ -408,7 +408,7 @@ def _parse_enc_template(enctype): cur_type["required"] = __parse_field_ent(parse_ent(line, "require")) if not cur_type["required"]: # An error occured parsing the require line. - print "Invalid 'required' line found in template %s" % enctype + print("Invalid 'required' line found in template %s" % enctype) continue elif line.startswith("optional"): cur_type["optional"] = __parse_field_ent(parse_ent(line, @@ -416,7 +416,7 @@ def _parse_enc_template(enctype): field_type="optional") if not cur_type["optional"]: # An error occured parsing the optional line. - print "Invalid 'optional' line found in template %s" % enctype + print("Invalid 'optional' line found in template %s" % enctype) continue elif line.startswith("protected"): cur_type["protected"] = __parse_field_ent( @@ -425,17 +425,17 @@ def _parse_enc_template(enctype): ) if not cur_type["protected"]: # An error occured parsing the protected line. - print "Invalid 'protected' line found in template %s" % enctype + print("Invalid 'protected' line found in template %s" % enctype) continue elif line.startswith("----"): # We're done. break f.close() if not cur_type["required"]: - print "Failed to find a 'require' line in template %s" % enctype + print("Failed to find a 'require' line in template %s" % enctype) return None if not cur_type["name"]: - print "Failed to find a 'name' line in template %s" % enctype + print("Failed to find a 'name' line in template %s" % enctype) return None else: return cur_type @@ -476,9 +476,9 @@ def sanitize_escaped(s): def to_unicode(x): """ Attempts to convert a string to utf-8. """ # If this is a unicode string, encode it and return - if not isinstance(x, basestring): + if not isinstance(x, str): return x - if isinstance(x, unicode): + if isinstance(x, str): return x.encode('utf-8') x = sanitize_escaped(x) @@ -500,7 +500,7 @@ def to_unicode(x): def RenameProcess(new_name): """ Renames the process calling the function to the given name. """ if 'linux' not in sys.platform: - print 'Unsupported platform' + print('Unsupported platform') return False try: import ctypes @@ -509,7 +509,7 @@ def RenameProcess(new_name): libc.prctl(15, new_name, 0, 0, 0) return True except: - print "rename failed" + print("rename failed") return False def detect_desktop_environment(): @@ -639,7 +639,7 @@ def izip_longest(*args, **kwds): fillers = repeat(fillvalue) iters = [chain(it, sentinel(), fillers) for it in args] try: - for tup in izip(*iters): + for tup in zip(*iters): yield tup except IndexError: pass @@ -651,4 +651,4 @@ def grouper(n, iterable, fillvalue=None): """ args = [iter(iterable)] * n - return izip_longest(fillvalue=fillvalue, *args) + return zip_longest(fillvalue=fillvalue, *args) diff --git a/wicd/monitor.py b/wicd/monitor.py index af573eb..89ecccc 100755 --- a/wicd/monitor.py +++ b/wicd/monitor.py @@ -55,8 +55,8 @@ def diewithdbus(func): ret = func(self, *__args, **__kargs) self.__lost_dbus_count = 0 return ret - except DBusException, e: - print "Caught exception %s" % str(e) + except DBusException as e: + print("Caught exception %s" % str(e)) if not hasattr(self, "__lost_dbus_count"): self.__lost_dbus_count = 0 if self.__lost_dbus_count > 3: @@ -188,7 +188,7 @@ class ConnectionStatus(object): # If we haven't gotten any signal 4 runs in a row (12 seconds), # try to reconnect. self.connection_lost_counter += 1 - print self.connection_lost_counter + print(self.connection_lost_counter) if self.connection_lost_counter >= 4 and daemon.GetAutoReconnect(): wireless.DisconnectWireless() self.connection_lost_counter = 0 @@ -218,7 +218,7 @@ class ConnectionStatus(object): wifi_ip = None if daemon.GetSuspend(): - print "Suspended." + print("Suspended.") state = misc.SUSPENDED return self.update_state(state) @@ -251,7 +251,7 @@ class ConnectionStatus(object): # Don't trigger it if the gui is open, because autoconnect # is disabled while it's open. if not daemon.GetGUIOpen(): - print 'Killing wireless connection to switch to wired...' + print('Killing wireless connection to switch to wired...') wireless.DisconnectWireless() daemon.AutoConnect(False, reply_handler=lambda *a:None, error_handler=lambda *a:None) @@ -291,7 +291,7 @@ class ConnectionStatus(object): self.reconnect_tries = 0 info = [str(wired_ip)] else: - print 'ERROR: Invalid state!' + print('ERROR: Invalid state!') return True daemon.SetConnectionStatus(state, info) @@ -345,14 +345,14 @@ class ConnectionStatus(object): # Some checks to keep reconnect retries from going crazy. if (self.reconnect_tries > 3 and (time.time() - self.last_reconnect_time) < 200): - print "Throttling autoreconnect" + print("Throttling autoreconnect") return self.reconnecting = True daemon.SetCurrentInterface('') if daemon.ShouldAutoReconnect(): - print 'Starting automatic reconnect process' + print('Starting automatic reconnect process') self.last_reconnect_time = time.time() self.reconnect_tries += 1 @@ -362,10 +362,10 @@ class ConnectionStatus(object): if from_wireless and cur_net_id > -1: # make sure disconnect scripts are run # before we reconnect - print 'Disconnecting from network' + print('Disconnecting from network') wireless.DisconnectWireless() - print 'Trying to reconnect to last used wireless ' + \ - 'network' + print('Trying to reconnect to last used wireless ' + \ + 'network') wireless.ConnectWireless(cur_net_id) else: daemon.AutoConnect(True, reply_handler=reply_handle, diff --git a/wicd/networking.py b/wicd/networking.py index f7a6579..3e05af3 100644 --- a/wicd/networking.py +++ b/wicd/networking.py @@ -50,10 +50,10 @@ import os from signal import SIGTERM # wicd imports -import misc +from . import misc import wpath -from backend import BackendManager -from translations import _ +from .backend import BackendManager +from .translations import _ if __name__ == '__main__': wpath.chdir(__file__) @@ -123,9 +123,9 @@ def expand_script_macros(script, msg, bssid, essid): """ def repl(match): macro = match.group(1).lower() - if macro_dict.has_key(macro): + if macro in macro_dict: return macro_dict[macro] - print 'Warning: found illegal macro %s in %s script' % (macro, msg) + print('Warning: found illegal macro %s in %s script' % (macro, msg)) return match.group() macro_dict = { 'script' : msg, @@ -133,7 +133,7 @@ def expand_script_macros(script, msg, bssid, essid): 'essid' : essid } regex = re.compile(r'%\{([a-zA-Z0-9]+)\}') expanded = regex.sub(repl, script) - print "Expanded '%s' to '%s'" % (script, expanded) + print("Expanded '%s' to '%s'" % (script, expanded)) return expanded @@ -223,7 +223,7 @@ class Controller(object): misc.ExecuteScripts(wpath.predisconnectscripts, self.debug, extra_parameters=(nettype, name, mac)) if self.pre_disconnect_script: - print 'Running pre-disconnect script' + print('Running pre-disconnect script') misc.ExecuteScript(expand_script_macros(self.pre_disconnect_script, 'pre-disconnection', mac, name), @@ -237,7 +237,7 @@ class Controller(object): misc.ExecuteScripts(wpath.postdisconnectscripts, self.debug, extra_parameters=(nettype, name, mac)) if self.post_disconnect_script: - print 'Running post-disconnect script' + print('Running post-disconnect script') misc.ExecuteScript(expand_script_macros(self.post_disconnect_script, 'post-disconnection', mac, name), @@ -249,7 +249,7 @@ class Controller(object): def KillDHCP(self): """ Kill the managed DHCP client if its in a connecting state. """ - print 'running kill dhcp.' + print('running kill dhcp.') if (self.connecting_thread.is_connecting and self.iface.dhcp_object): if self.iface.dhcp_object.poll() is None: @@ -403,14 +403,14 @@ class ConnectThread(threading.Thread): routing entry is created. """ - print 'Setting false IP...' + print('Setting false IP...') self.SetStatus('resetting_ip_address') iface.SetAddress('0.0.0.0') @abortable def put_iface_down(self, iface): """ Puts the given interface down. """ - print 'Putting interface down' + print('Putting interface down') self.SetStatus('interface_down') iface.Down() @@ -430,7 +430,7 @@ class ConnectThread(threading.Thread): """ if script: - print 'Executing %s script' % (msg) + print('Executing %s script' % (msg)) misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid), self.debug) @@ -438,7 +438,7 @@ class ConnectThread(threading.Thread): def flush_routes(self, iface): """ Flush the routes for both wired/wireless interfaces. """ self.SetStatus('flushing_routing_table') - print 'Flushing the routing table...' + print('Flushing the routing table...') iface.FlushRoutes() @abortable @@ -446,7 +446,7 @@ class ConnectThread(threading.Thread): """ Set the broadcast address for the given interface. """ if not self.network.get('broadcast') == None: self.SetStatus('setting_broadcast_address') - print 'Setting the broadcast address...' + self.network['broadcast'] + print('Setting the broadcast address...' + self.network['broadcast']) iface.SetAddress(broadcast=self.network['broadcast']) @abortable @@ -458,10 +458,10 @@ class ConnectThread(threading.Thread): """ if self.network.get('ip'): self.SetStatus('setting_static_ip') - print 'Setting static IP : ' + self.network['ip'] + print('Setting static IP : ' + self.network['ip']) iface.SetAddress(self.network['ip'], self.network['netmask']) if self.network.get('gateway'): - print 'Setting default gateway : ' + self.network['gateway'] + print('Setting default gateway : ' + self.network['gateway']) iface.SetDefaultRoute(self.network['gateway']) else: # Run dhcp... @@ -472,10 +472,10 @@ class ConnectThread(threading.Thread): self.network['dhcphostname'] = os.uname()[1] if self.network['usedhcphostname']: hname = self.network['dhcphostname'] - print "Running DHCP with hostname", hname + print("Running DHCP with hostname", hname) else: hname = None - print "Running DHCP with NO hostname" + print("Running DHCP with NO hostname") # Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf staticdns = False @@ -525,7 +525,7 @@ class ConnectThread(threading.Thread): @abortable def release_dhcp_clients(self, iface): """ Release all running dhcp clients. """ - print "Releasing DHCP leases..." + print("Releasing DHCP leases...") iface.ReleaseDHCP() def connect_aborted(self, reason): @@ -536,7 +536,7 @@ class ConnectThread(threading.Thread): self.is_aborted = True self.connect_result = reason self.is_connecting = False - print 'exiting connection thread' + print('exiting connection thread') def abort_connection(self, reason=""): """ Schedule a connection abortion for the given reason. """ @@ -556,13 +556,13 @@ class ConnectThread(threading.Thread): @abortable def stop_wpa(self, iface): """ Stops wpa_supplicant. """ - print 'Stopping wpa_supplicant' + print('Stopping wpa_supplicant') iface.StopWPA() @abortable def put_iface_up(self, iface): """ Bring up given interface. """ - print 'Putting interface up...' + print('Putting interface up...') self.SetStatus('interface_up') iface.Up() for x in range(0, 5): @@ -572,7 +572,7 @@ class ConnectThread(threading.Thread): self.abort_if_needed() # If we get here, the interface never came up - print "WARNING: Timed out waiting for interface to come up" + print("WARNING: Timed out waiting for interface to come up") class Wireless(Controller): @@ -657,7 +657,7 @@ class Wireless(Controller): # Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX" essid = misc.Noneify(essid) if essid is not None: - print 'Setting hidden essid ' + essid + print('Setting hidden essid ' + essid) wiface.SetEssid(essid) # sleep for a bit; scanning to fast will result in nothing time.sleep(1) @@ -792,23 +792,23 @@ class Wireless(Controller): """ wiface = self.wiface - print 'Creating ad-hoc network' - print 'Stopping dhcp client and wpa_supplicant' + print('Creating ad-hoc network') + print('Stopping dhcp client and wpa_supplicant') wiface.ReleaseDHCP() wiface.StopWPA() - print 'Putting wireless interface down' + print('Putting wireless interface down') wiface.Down() - print 'Setting mode, channel, and essid' + print('Setting mode, channel, and essid') wiface.SetMode('ad-hoc') wiface.SetChannel(channel) wiface.SetEssid(essid) # Right now it just assumes you're using WEP if enc_used: - print 'Setting encryption key' + print('Setting encryption key') wiface.SetKey(key) - print 'Putting interface up' + print('Putting interface up') wiface.Up() - print 'Setting IP address' + print('Setting IP address') wiface.SetAddress(ip, '255.255.255.0') def DetectWirelessInterface(self): @@ -843,10 +843,10 @@ class Wireless(Controller): action = 'block' for t in types: cmd = ['rfkill', action, t] - print "rfkill: %sing %s" % (action, t) + print("rfkill: %sing %s" % (action, t)) misc.Run(cmd) return True - except Exception, e: + except Exception as e: raise e return False @@ -858,9 +858,8 @@ class Wireless(Controller): """ cmd = 'rfkill list' rfkill_out = misc.Run(cmd) - soft_blocks = filter(lambda x: x.startswith('Soft'), - rfkill_out.split('\t')) - for line in map(lambda x: x.strip(), soft_blocks): + soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')] + for line in [x.strip() for x in soft_blocks]: if line.endswith('yes'): return True return False @@ -983,7 +982,7 @@ class WirelessConnectThread(ConnectThread): if self.network.get('enctype'): self.SetStatus('validating_authentication') if not wiface.ValidateAuthentication(time.time()): - print "connect result is %s" % self.connect_result + print("connect result is %s" % self.connect_result) if not self.connect_result or self.connect_result == 'failed': self.abort_connection('bad_pass') @@ -1003,9 +1002,9 @@ class WirelessConnectThread(ConnectThread): self.network['bssid'], self.network['essid']) self.SetStatus('done') - print 'Connecting thread exiting.' + print('Connecting thread exiting.') if self.debug: - print "IP Address is: " + str(wiface.GetIP()) + print("IP Address is: " + str(wiface.GetIP())) self.connect_result = "success" self.is_connecting = False @@ -1020,17 +1019,17 @@ class WirelessConnectThread(ConnectThread): """ if self.network.get('gateway') and self.should_verify_ap: self.SetStatus('verifying_association') - print "Verifying AP association..." + print("Verifying AP association...") for tries in range(1, 11): - print "Attempt %d of 10..." % tries + print("Attempt %d of 10..." % tries) retcode = self.iface.VerifyAPAssociation(self.network['gateway']) if retcode == 0: - print "Successfully associated." + print("Successfully associated.") break time.sleep(1) #TODO this should be in wnettools.py if retcode: - print "Connection Failed: Failed to ping the access point!" + print("Connection Failed: Failed to ping the access point!") # Clean up before aborting. iface.SetAddress('0.0.0.0') iface.FlushRoutes() @@ -1039,7 +1038,7 @@ class WirelessConnectThread(ConnectThread): iface.StopWPA() self.abort_connection('association_failed') else: - print 'not verifying' + print('not verifying') @abortable def generate_psk_and_authenticate(self, wiface): @@ -1052,22 +1051,22 @@ class WirelessConnectThread(ConnectThread): # Check to see if we need to generate a PSK (only for non-ralink # cards). if self.debug: - print "enctype is %s" % self.network.get('enctype') + print("enctype is %s" % self.network.get('enctype')) if self.network.get('key') and \ 'wpa' in str(self.network.get('enctype')): self.SetStatus('generating_psk') - print 'Generating psk...' + print('Generating psk...') self.network['psk'] = wiface.GeneratePSK(self.network) if not self.network.get('psk'): self.network['psk'] = self.network['key'] - print 'WARNING: PSK generation failed! Falling back to ' + \ + print('WARNING: PSK generation failed! Falling back to ' + \ 'wireless key.\nPlease report this error to the wicd ' + \ - 'developers!' + 'developers!') # Generate the wpa_supplicant file... if self.network.get('enctype'): self.SetStatus('generating_wpa_config') - print 'Attempting to authenticate...' + print('Attempting to authenticate...') wiface.Authenticate(self.network) @@ -1248,9 +1247,9 @@ class WiredConnectThread(ConnectThread): 'wired') self.SetStatus('done') - print 'Connecting thread exiting.' + print('Connecting thread exiting.') if self.debug: - print "IP Address is: " + str(liface.GetIP()) + print("IP Address is: " + str(liface.GetIP())) self.connect_result = "success" self.is_connecting = False diff --git a/wicd/suspend.py b/wicd/suspend.py index 675a354..d032668 100755 --- a/wicd/suspend.py +++ b/wicd/suspend.py @@ -32,9 +32,9 @@ try: bus = dbus.SystemBus() 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.' +except Exception as e: + print("Exception caught: %s" % str(e), file=sys.stderr) + print('Could not connect to daemon.', file=sys.stderr) sys.exit(1) @@ -43,7 +43,7 @@ if __name__ == '__main__': daemon.Disconnect() daemon.SetForcedDisconnect(False) daemon.SetSuspend(True) - except Exception, e: - print >> sys.stderr, "Exception caught: %s" % str(e) - print >> sys.stderr, 'Error setting suspend.' + except Exception as e: + print("Exception caught: %s" % str(e), file=sys.stderr) + print('Error setting suspend.', file=sys.stderr) sys.exit(2) diff --git a/wicd/translations.py b/wicd/translations.py index 0ae08dc..21f47db 100644 --- a/wicd/translations.py +++ b/wicd/translations.py @@ -44,9 +44,9 @@ def get_gettext(): lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES', 'LC_ALL', 'LANG', 'LANGUAGE')) - except ValueError, e: - print str(e) - print "Default locale unavailable, falling back to en_US" + except ValueError as e: + print(str(e)) + print("Default locale unavailable, falling back to en_US") if (lc): langs += [lc] langs += ["en_US"] diff --git a/wicd/wicd-daemon.py b/wicd/wicd-daemon.py index 614ac84..0b30312 100644 --- a/wicd/wicd-daemon.py +++ b/wicd/wicd-daemon.py @@ -133,7 +133,7 @@ class WicdDaemon(dbus.service.Object, object): # Scan since we just got started if not auto_connect: - print "--no-autoconnect detected, not autoconnecting..." + print("--no-autoconnect detected, not autoconnecting...") self.SetForcedDisconnect(True) self.wireless_bus.Scan() @@ -161,7 +161,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetWiredInterface(self, interface): """ Sets the wired interface for the daemon to use. """ - print "setting wired interface %s" % (str(interface)) + print("setting wired interface %s" % (str(interface))) # Set it to a blank string, otherwise a network card named "None" will be searched self.wired.wired_interface = noneToBlankString(interface) self.config.set("Settings", "wired_interface", interface, write=True) @@ -169,7 +169,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetWirelessInterface(self, interface): """ Sets the wireless interface the daemon will use. """ - print "setting wireless interface %s" % (str(interface)) + print("setting wireless interface %s" % (str(interface))) # Set it to a blank string, otherwise a network card named "None" will be searched self.wifi.wireless_interface = noneToBlankString(interface) self.config.set("Settings", "wireless_interface", interface, write=True) @@ -177,14 +177,14 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetWPADriver(self, driver): """ Sets the wpa driver the wpa_supplicant will use. """ - print "setting wpa driver", str(driver) + print("setting wpa driver", str(driver)) self.wifi.wpa_driver = driver self.config.set("Settings", "wpa_driver", driver, write=True) @dbus.service.method('org.wicd.daemon') def SetUseGlobalDNS(self, use): """ Sets a boolean which determines if global DNS is enabled. """ - print 'setting use global dns to', use + print('setting use global dns to', use) use = misc.to_bool(use) self.config.set("Settings", "use_global_dns", use, write=True) self.use_global_dns = use @@ -195,7 +195,7 @@ class WicdDaemon(dbus.service.Object, object): def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, dns_dom =None, search_dom=None): """ Sets the global dns addresses. """ - print "setting global dns" + print("setting global dns") self.config.set("Settings", "global_dns_1", misc.noneToString(dns1)) self.dns1 = dns1 self.wifi.global_dns_1 = dns1 @@ -218,26 +218,26 @@ class WicdDaemon(dbus.service.Object, object): self.search_dom = search_dom self.wifi.global_search_dom = search_dom self.wired.global_search_dom = search_dom - print 'global dns servers are', dns1, dns2, dns3 - print 'domain is %s' % dns_dom - print 'search domain is %s' % search_dom + print('global dns servers are', dns1, dns2, dns3) + print('domain is %s' % dns_dom) + print('search domain is %s' % search_dom) self.config.write() @dbus.service.method('org.wicd.daemon') def SetBackend(self, backend): """ Sets a new backend. """ - print "setting backend to %s" % backend + 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: - print "ERROR: no backends available!" + print("ERROR: no backends available!") return else: - print "Fell back to backend %s" % backend + print("Fell back to backend %s" % backend) self.config.set("Settings", "backend", backend, write=True) if backend != self.GetCurrentBackend(): self.suspended = True @@ -364,18 +364,18 @@ class WicdDaemon(dbus.service.Object, object): fails it tries a wireless connection. """ - print "Autoconnecting..." + print("Autoconnecting...") if self.CheckIfConnecting(): if self.debug_mode: - print 'Already connecting, doing nothing.' + print('Already connecting, doing nothing.') return if self.wired_bus.CheckPluggedIn(): if self.debug_mode: - print "Starting wired autoconnect..." + print("Starting wired autoconnect...") self._wired_autoconnect(fresh) else: if self.debug_mode: - print "Starting wireless autoconnect..." + print("Starting wireless autoconnect...") self.wireless_bus._wireless_autoconnect(fresh) @dbus.service.method('org.wicd.daemon') @@ -392,7 +392,7 @@ class WicdDaemon(dbus.service.Object, object): and wait for the user to initiate reconnection. """ - print 'setting automatically reconnect when connection drops %s' % value + print('setting automatically reconnect when connection drops %s' % value) self.config.set("Settings", "auto_reconnect", misc.to_bool(value), write=True) self.auto_reconnect = misc.to_bool(value) @@ -416,7 +416,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def CancelConnect(self): """ Cancels the wireless connection attempt """ - print 'canceling connection attempt' + print('canceling connection attempt') if self.wifi.connecting_thread: self.wifi.connecting_thread.should_die = True self.wifi.ReleaseDHCP() @@ -478,7 +478,7 @@ class WicdDaemon(dbus.service.Object, object): """ if self.debug_mode and value: - print "Forced disconnect on" + print("Forced disconnect on") self.forced_disconnect = bool(value) @dbus.service.method('org.wicd.daemon') @@ -666,7 +666,7 @@ class WicdDaemon(dbus.service.Object, object): See misc.py for a definition of the constants. """ - print "Setting dhcp client to %i" % (int(client)) + print("Setting dhcp client to %i" % (int(client))) self.dhcp_client = int(client) self.wifi.dhcp_client = int(client) self.wired.dhcp_client = int(client) @@ -730,7 +730,7 @@ class WicdDaemon(dbus.service.Object, object): # attempt to smartly connect to a wired network # by using various wireless networks detected # and by using plugged in USB devices - print self.LastScan + print(self.LastScan) if self.GetWiredAutoConnectMethod() == 2 and \ not self.GetNeedWiredProfileChooser(): self.LaunchChooser() @@ -740,8 +740,8 @@ class WicdDaemon(dbus.service.Object, object): elif self.GetWiredAutoConnectMethod() == 1: network = wiredb.GetDefaultWiredNetwork() if not network: - print "Couldn't find a default wired connection," + \ - " wired autoconnect failed." + print("Couldn't find a default wired connection," + \ + " wired autoconnect failed.") self.wireless_bus._wireless_autoconnect(fresh) return @@ -749,14 +749,14 @@ class WicdDaemon(dbus.service.Object, object): else: network = wiredb.GetLastUsedWiredNetwork() if not network: - print "no previous wired profile available, wired " + \ - "autoconnect failed." + print("no previous wired profile available, wired " + \ + "autoconnect failed.") self.wireless_bus._wireless_autoconnect(fresh) return wiredb.ReadWiredNetworkProfile(network) wiredb.ConnectWired() - print "Attempting to autoconnect with wired interface..." + print("Attempting to autoconnect with wired interface...") self.auto_connecting = True time.sleep(1.5) try: @@ -818,7 +818,7 @@ class WicdDaemon(dbus.service.Object, object): @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 + print("Sending connection attempt result %s" % result) @dbus.service.method("org.wicd.daemon") @dbus.service.signal(dbus_interface="org.wicd.daemon", signature='') @@ -828,7 +828,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='') def LaunchChooser(self): """ Emits the wired profile chooser dbus signal. """ - print 'calling wired profile chooser' + print('calling wired profile chooser') self.SetNeedWiredProfileChooser(True) @dbus.service.signal(dbus_interface="org.wicd.daemon", signature='') @@ -926,38 +926,38 @@ class WicdDaemon(dbus.service.Object, object): app_conf.write() if os.path.isfile(wireless_conf): - print "Wireless configuration file found..." + print("Wireless configuration file found...") else: - print "Wireless configuration file not found, creating..." + print("Wireless configuration file not found, creating...") open(wireless_conf, "w").close() if os.path.isfile(wired_conf): - print "Wired configuration file found..." + print("Wired configuration file found...") else: - print "Wired configuration file not found, creating a default..." + print("Wired configuration file not found, creating a default...") # Create the file and a default profile open(wired_conf, "w").close() b_wired.CreateWiredNetworkProfile("wired-default", default=True) if not os.path.isfile(dhclient_conf): - print "dhclient.conf.template not found, copying..." + print("dhclient.conf.template not found, copying...") shutil.copy(dhclient_conf + ".default", dhclient_conf) # Hide the files, so the keys aren't exposed. - print "chmoding configuration files 0600..." - os.chmod(app_conf.get_config(), 0600) - os.chmod(wireless_conf, 0600) - os.chmod(wired_conf, 0600) - os.chmod(dhclient_conf, 0644) + print("chmoding configuration files 0600...") + os.chmod(app_conf.get_config(), 0o600) + os.chmod(wireless_conf, 0o600) + os.chmod(wired_conf, 0o600) + os.chmod(dhclient_conf, 0o644) # Make root own them - print "chowning configuration files root:root..." + print("chowning configuration files root:root...") os.chown(app_conf.get_config(), 0, 0) os.chown(wireless_conf, 0, 0) os.chown(wired_conf, 0, 0) os.chown(dhclient_conf, 0, 0) - print "Using wireless interface..." + self.GetWirelessInterface() - print "Using wired interface..." + self.GetWiredInterface() + print("Using wireless interface..." + self.GetWirelessInterface()) + print("Using wired interface..." + self.GetWiredInterface()) ############################## ###### Wireless Daemon ####### @@ -1004,10 +1004,10 @@ class WirelessDaemon(dbus.service.Object, object): """ if self._scanning: if self.debug_mode: - print "scan already in progress, skipping" + print("scan already in progress, skipping") return False if self.debug_mode: - print 'scanning start' + print('scanning start') self.SendStartScanSignal() if sync: self._sync_scan() @@ -1025,8 +1025,8 @@ class WirelessDaemon(dbus.service.Object, object): scan = self.wifi.Scan(str(self.hidden_essid)) self.LastScan = scan if self.debug_mode: - print 'scanning done' - print 'found ' + str(len(scan)) + ' networks:' + print('scanning done') + print('found ' + str(len(scan)) + ' networks:') for i, network in enumerate(scan): self.ReadWirelessNetworkProfile(i) self.SendEndScanSignal() @@ -1115,8 +1115,8 @@ class WirelessDaemon(dbus.service.Object, object): # We don't write script settings here. prop = misc.sanitize_config(prop) if prop.endswith('script'): - print 'Setting script properties through the daemon' \ - + ' is not permitted.' + print('Setting script properties through the daemon' \ + + ' is not permitted.') return False # whitelist some props that need different handling if prop in ('key_index', ): @@ -1130,9 +1130,9 @@ class WirelessDaemon(dbus.service.Object, object): """ Returns an automatically detected wireless interface. """ iface = self.wifi.DetectWirelessInterface() if iface: - print 'Automatically detected wireless interface ' + iface + print('Automatically detected wireless interface ' + iface) else: - print "Couldn't detect a wireless interface." + print("Couldn't detect a wireless interface.") return str(iface) @dbus.service.method('org.wicd.daemon.wireless') @@ -1174,11 +1174,11 @@ class WirelessDaemon(dbus.service.Object, object): def GetCurrentNetworkID(self, iwconfig=None): """ Returns the id of the current network, or -1 if its not found. """ currentESSID = self.GetCurrentNetwork(iwconfig) - for x in xrange(0, len(self.LastScan)): + for x in range(0, len(self.LastScan)): if self.LastScan[x]['essid'] == currentESSID: return x if self.debug_mode: - print 'GetCurrentNetworkID: Returning -1, current network not found' + print('GetCurrentNetworkID: Returning -1, current network not found') return -1 @dbus.service.method('org.wicd.daemon.wireless') @@ -1209,8 +1209,8 @@ class WirelessDaemon(dbus.service.Object, object): 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']) + 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() @@ -1265,7 +1265,7 @@ class WirelessDaemon(dbus.service.Object, object): return "500: Profile Not Found" for x in self.config.options(section): - if not cur_network.has_key(x) or x.endswith("script"): + if x not in cur_network or x.endswith("script"): cur_network[x] = misc.Noneify(self.config.get(section, x)) for option in ['use_static_dns', 'use_global_dns', 'encryption', 'use_settings_globally']: @@ -1325,8 +1325,8 @@ class WirelessDaemon(dbus.service.Object, object): """ Writes a particular wireless property to disk. """ option = misc.sanitize_config(option) if option.endswith("script"): - print 'You cannot save script information to disk through ' + \ - 'the daemon.' + print('You cannot save script information to disk through ' + \ + 'the daemon.') return config = self.config cur_network = self.LastScan[nid] @@ -1376,8 +1376,8 @@ class WirelessDaemon(dbus.service.Object, object): def DeleteWirelessNetwork(self, section): """ Deletes a wireless network section. """ section = misc.to_unicode(section) - print "Deleting wireless settings for %s (%s)" % \ - (self.config.get(section, 'essid'), str(section)) + print("Deleting wireless settings for %s (%s)" % \ + (self.config.get(section, 'essid'), str(section))) self.config.remove_section(section) self.config.write() @@ -1395,10 +1395,10 @@ class WirelessDaemon(dbus.service.Object, object): def _wireless_autoconnect(self, fresh=True): """ Attempts to autoconnect to a wireless network. """ - print "No wired connection present, attempting to autoconnect " + \ - "to wireless network" + print("No wired connection present, attempting to autoconnect " + \ + "to wireless network") if self.wifi.wireless_interface is None: - print 'Autoconnect failed because wireless interface returned None' + print('Autoconnect failed because wireless interface returned None') return if fresh: self.Scan(sync=True) @@ -1406,19 +1406,19 @@ class WirelessDaemon(dbus.service.Object, object): for x, network in enumerate(self.LastScan): if self.config.has_section(network['bssid']): if self.debug_mode: - print network["essid"] + ' has profile' + print(network["essid"] + ' has profile') if bool(network.get('automatic')): if network.get('never'): - print network["essid"],'marked never connect' + print(network["essid"],'marked never connect') continue else: - print network["essid"],'has no never connect value' - print 'trying to automatically connect to...' + \ - network["essid"] + print(network["essid"],'has no never connect value') + print('trying to automatically connect to...' + \ + network["essid"]) self.ConnectWireless(x) time.sleep(1) return - print "Unable to autoconnect, you'll have to manually connect" + print("Unable to autoconnect, you'll have to manually connect") ########################### ###### Wired Daemon ####### @@ -1481,9 +1481,9 @@ class WiredDaemon(dbus.service.Object, object): """ Returns an automatically detected wireless interface. """ iface = self.wired.DetectWiredInterface() if iface: - print 'automatically detected wired interface ' + str(iface) + print('automatically detected wired interface ' + str(iface)) else: - print "Couldn't detect a wired interface." + print("Couldn't detect a wired interface.") return str(iface) @dbus.service.method('org.wicd.daemon.wired') @@ -1492,13 +1492,13 @@ class WiredDaemon(dbus.service.Object, object): if self.WiredNetwork: prop = misc.sanitize_config(prop) if prop.endswith('script'): - print 'Setting script properties through the daemon' \ - + ' is not permitted.' + print('Setting script properties through the daemon' \ + + ' is not permitted.') return False self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value)) return True else: - print 'SetWiredProperty: WiredNetwork does not exist' + print('SetWiredProperty: WiredNetwork does not exist') return False @dbus.service.method('org.wicd.daemon.wired') @@ -1508,7 +1508,7 @@ class WiredDaemon(dbus.service.Object, object): value = self.WiredNetwork.get(prop) return value else: - print 'GetWiredProperty: WiredNetwork does not exist' + print('GetWiredProperty: WiredNetwork does not exist') return False @dbus.service.method('org.wicd.daemon.wired') @@ -1572,7 +1572,7 @@ class WiredDaemon(dbus.service.Object, object): if not profilename: return False profilename = misc.to_unicode(profilename) - print "Creating wired profile for " + profilename + print("Creating wired profile for " + profilename) if self.config.has_section(profilename): return False @@ -1624,7 +1624,7 @@ class WiredDaemon(dbus.service.Object, object): def DeleteWiredNetworkProfile(self, profilename): """ Deletes a wired network profile. """ profilename = misc.to_unicode(profilename) - print "Deleting wired profile for " + str(profilename) + print("Deleting wired profile for " + str(profilename)) self.config.remove_section(profilename) self.config.write() @@ -1638,10 +1638,10 @@ class WiredDaemon(dbus.service.Object, object): profilename = profilename.strip() if not profilename: self.config.write() - print "Warning: Bad wired profile name given, ignoring." + print("Warning: Bad wired profile name given, ignoring.") return "500: Bad Profile name" if self.debug_mode: - print "saving wired profile %s" % profilename + print("saving wired profile %s" % profilename) profilename = misc.to_unicode(profilename) self.config.remove_section(profilename) self.config.add_section(profilename) @@ -1662,7 +1662,7 @@ class WiredDaemon(dbus.service.Object, object): profilename = misc.to_unicode(profilename) if self.config.has_section(profilename): if self.debug_mode: - print "Reading wired profile %s" % profilename + print("Reading wired profile %s" % profilename) for x in self.config.options(profilename): profile[x] = misc.Noneify(self.config.get(profilename, x)) profile['use_global_dns'] = bool(profile.get('use_global_dns')) @@ -1698,7 +1698,7 @@ class WiredDaemon(dbus.service.Object, object): def usage(): """ Print help screen. """ - print """ + print(""" wicd %s wireless (and wired) connection daemon. @@ -1710,7 +1710,7 @@ Arguments: \t-n\t--no-poll\tDon't monitor network status. \t-o\t--no-stdout\tDon't redirect stdout. \t-h\t--help\t\tPrint this help. -""" % (wpath.version + ' (bzr-r%s)' % wpath.revision) +""" % (wpath.version + ' (bzr-r%s)' % wpath.revision)) def daemonize(): """ Disconnect from the controlling terminal. @@ -1729,8 +1729,8 @@ def daemonize(): pid = os.fork() if pid > 0: sys.exit(0) - except OSError, e: - print >> sys.stderr, "Fork #1 failed: %d (%s)" % (e.errno, e.strerror) + except OSError as e: + print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) sys.exit(1) # Decouple from parent environment to stop us from being a zombie. @@ -1751,8 +1751,8 @@ def daemonize(): else: os.umask(0) os.chdir('/') - except OSError, e: - print >> sys.stderr, "Fork #2 failed: %d (%s)" % (e.errno, e.strerror) + except OSError as e: + print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) sys.exit(1) sys.stdin.close() @@ -1795,9 +1795,9 @@ def main(argv): os.symlink(dest, backup_location) else: shutil.copy2('/etc/resolv.conf', backup_location) - os.chmod(backup_location, 0644) + os.chmod(backup_location, 0o644) except IOError: - print 'error backing up resolv.conf' + print('error backing up resolv.conf') do_daemonize = True redirect_stderr = True @@ -1852,9 +1852,9 @@ def main(argv): os.symlink(dest, '/etc/resolv.conf') else: shutil.move(backup_location, '/etc/resolv.conf') - os.chmod('/etc/resolv.conf', 0644) + os.chmod('/etc/resolv.conf', 0o644) except IOError: - print 'error restoring resolv.conf' + print('error restoring resolv.conf') # connect to dbus, trigger a disconnect, then knock out the daemon from wicd import dbusmanager @@ -1869,8 +1869,8 @@ def main(argv): sys.exit(0) if os.path.exists(wpath.pidfile): - print 'It seems like the daemon is already running.' - print 'If it is not, please remove %s and try again.' % wpath.pidfile + print('It seems like the daemon is already running.') + print('If it is not, please remove %s and try again.' % wpath.pidfile) sys.exit(1) if not os.path.exists(wpath.networks): @@ -1883,13 +1883,13 @@ def main(argv): logpath = os.path.join(wpath.log, 'wicd.log') if not os.path.exists(wpath.log): os.makedirs(wpath.log) - os.chmod(wpath.log, 0755) + os.chmod(wpath.log, 0o755) output = ManagedStdio(logpath) if os.path.exists(logpath): try: os.chmod(logpath, int(wpath.log_perms, 8)) except OSError: - print 'unable to chmod log file to %s' % wpath.log_perms + print('unable to chmod log file to %s' % wpath.log_perms) try: if wpath.log_group: @@ -1897,18 +1897,18 @@ def main(argv): group = grp.getgrnam(wpath.log_group) os.chown(logpath, 0, group[2]) except OSError: - print 'unable to chown log file to %s' % group[2] + print('unable to chown log file to %s' % group[2]) if redirect_stdout: sys.stdout = output if redirect_stderr: sys.stderr = output - print '---------------------------' - print 'wicd initializing...' - print '---------------------------' + print('---------------------------') + print('wicd initializing...') + print('---------------------------') - print 'wicd is version', wpath.version, wpath.revision + print('wicd is version', wpath.version, wpath.revision) # Open the DBUS session bus = dbus.SystemBus() @@ -1933,22 +1933,22 @@ def main(argv): def on_exit(child_pid): """ Called when a SIGTERM is caught, kills monitor.py before exiting. """ if child_pid: - print 'Daemon going down, killing wicd-monitor...' + print('Daemon going down, killing wicd-monitor...') try: os.kill(child_pid, signal.SIGTERM) except OSError: pass - print 'Removing PID file...' + print('Removing PID file...') if os.path.exists(wpath.pidfile): os.remove(wpath.pidfile) - print 'Shutting down...' + print('Shutting down...') sys.exit(0) if __name__ == '__main__': if os.getuid() != 0: - print ("Root privileges are required for the daemon to run properly." + - " Exiting.") + print(("Root privileges are required for the daemon to run properly." + + " Exiting.")) sys.exit(1) gobject.threads_init() main(sys.argv) diff --git a/wicd/wnettools.py b/wicd/wnettools.py index e68efdf..3676e8c 100644 --- a/wicd/wnettools.py +++ b/wicd/wnettools.py @@ -41,8 +41,8 @@ import socket, fcntl import shutil import wpath -import misc -from misc import find_path +from . import misc +from .misc import find_path # Regular expressions. _re_mode = (re.I | re.M | re.S) @@ -129,7 +129,7 @@ def GetDefaultGateway(): gateway = None for line in lines: words = line.split() - print words + print(words) if not words: continue if words[0] == '0.0.0.0': @@ -137,7 +137,7 @@ def GetDefaultGateway(): break if not gateway: - print 'couldn\'t retrieve default gateway from route -n' + print('couldn\'t retrieve default gateway from route -n') return gateway def isWireless(devname): @@ -196,7 +196,7 @@ def GetWpaSupplicantDrivers(): try: output = output.split("drivers:")[1].split("options:")[0].strip() except KeyError: - print "Warning: Couldn't get list of valid wpa_supplicant drivers" + print("Warning: Couldn't get list of valid wpa_supplicant drivers") return [""] patt = re.compile("(\S+)\s+=.*") drivers = patt.findall(output) or [""] @@ -292,7 +292,7 @@ class BaseInterface(object): """ path = find_path(program) if not path and self.verbose: - print "WARNING: No path found for %s" % program + print("WARNING: No path found for %s" % program) return path @@ -363,8 +363,8 @@ class BaseInterface(object): # for specifing the hostname to be sent if client_name == "dhclient" and flavor: if hostname: - print 'attempting to set hostname with dhclient' - print 'using dhcpcd or another supported client may work better' + print('attempting to set hostname with dhclient') + print('using dhcpcd or another supported client may work better') dhclient_template = \ open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r') @@ -381,10 +381,10 @@ class BaseInterface(object): shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \ dhclient_conf_path) - os.chmod(dhclient_conf_path, 0644) + os.chmod(dhclient_conf_path, 0o644) if not client_name or not cmd: - print "WARNING: Failed to find a valid dhcp client!" + print("WARNING: Failed to find a valid dhcp client!") return "" if flavor == "connect": @@ -468,7 +468,7 @@ class BaseInterface(object): """ Check for the existence of wpa_cli """ self.wpa_cli_cmd = self._find_program_path("wpa_cli") if not self.wpa_cli_cmd: - print "wpa_cli not found. Authentication will not be validated." + print("wpa_cli not found. Authentication will not be validated.") def CheckRouteFlushTool(self): """ Check for a route flush tool. """ @@ -491,7 +491,7 @@ class BaseInterface(object): """ cmd = 'ifconfig ' + self.iface + ' up' if self.verbose: - print cmd + print(cmd) misc.Run(cmd) return True @@ -505,7 +505,7 @@ class BaseInterface(object): """ cmd = 'ifconfig ' + self.iface + ' down' if self.verbose: - print cmd + print(cmd) misc.Run(cmd) return True @@ -515,7 +515,7 @@ class BaseInterface(object): """ Runs ifconfig and returns the output. """ cmd = "ifconfig %s" % self.iface if self.verbose: - print cmd + print(cmd) return misc.Run(cmd) @neediface("") @@ -532,7 +532,7 @@ class BaseInterface(object): if not val: continue if not misc.IsValidIP(val): - print 'WARNING: Invalid IP address found, aborting!' + print('WARNING: Invalid IP address found, aborting!') return False cmd = ''.join(['ifconfig ', self.iface, ' ']) @@ -543,7 +543,7 @@ class BaseInterface(object): if broadcast: cmd = ''.join([cmd, 'broadcast ', broadcast, ' ']) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) def _parse_dhclient(self, pipe): @@ -567,7 +567,7 @@ class BaseInterface(object): if line == '': # Empty string means dhclient is done. dhclient_complete = True else: - print misc.to_unicode(line.strip('\n')) + print(misc.to_unicode(line.strip('\n'))) if line.startswith('bound'): dhclient_success = True dhclient_complete = True @@ -594,7 +594,7 @@ class BaseInterface(object): elif line.strip().lower().startswith('Operation failed.'): pump_success = False pump_complete = True - print misc.to_unicode(line) + print(misc.to_unicode(line)) return self._check_dhcp_result(pump_success) @@ -618,7 +618,7 @@ class BaseInterface(object): dhcpcd_complete = True elif line == '': dhcpcd_complete = True - print misc.to_unicode(line) + print(misc.to_unicode(line)) return self._check_dhcp_result(dhcpcd_success) @@ -642,7 +642,7 @@ class BaseInterface(object): udhcpc_complete = True elif line == '': udhcpc_complete = True - print line + print(line) return self._check_dhcp_result(udhcpc_success) @@ -657,10 +657,10 @@ class BaseInterface(object): """ if success: - print 'DHCP connection successful' + print('DHCP connection successful') return 'success' else: - print 'DHCP connection failed' + print('DHCP connection failed') return 'dhcp_failed' @neediface(False) @@ -677,7 +677,7 @@ class BaseInterface(object): """ cmd = self._get_dhcp_command('connect', hostname, staticdns) if self.verbose: - print cmd + 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, @@ -690,7 +690,7 @@ class BaseInterface(object): if DHCP_CLIENT in client_dict: ret = client_dict[DHCP_CLIENT](pipe) else: - print "ERROR: no dhcp client found" + print("ERROR: no dhcp client found") ret = None self.dhcp_object.wait() return ret @@ -700,7 +700,7 @@ class BaseInterface(object): """ Release the DHCP lease for this interface. """ cmd = self._get_dhcp_command("release") if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -711,10 +711,10 @@ class BaseInterface(object): elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: cmd = '%s del default dev %s' % (self.route_cmd, self.iface) else: - print "No route manipulation command available!" + print("No route manipulation command available!") return if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -727,7 +727,7 @@ class BaseInterface(object): if self.resolvconf_cmd: cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd'] if self.verbose: - print cmd + print(cmd) p = misc.Run(cmd, include_stderr=True, return_obj=True) p.communicate() @@ -757,10 +757,10 @@ class BaseInterface(object): if dns: if misc.IsValidIP(dns): if self.verbose: - print 'Setting DNS : ' + dns + print('Setting DNS : ' + dns) valid_dns_list.append("nameserver %s\n" % dns) else: - print 'DNS IP %s is not a valid IP address, skipping' % dns + print('DNS IP %s is not a valid IP address, skipping' % dns) if valid_dns_list: resolv_params += ''.join(valid_dns_list) @@ -768,7 +768,7 @@ class BaseInterface(object): if self.resolvconf_cmd: cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd'] if self.verbose: - print cmd + print(cmd) p = misc.Run(cmd, include_stderr=True, return_obj=True) p.communicate(input=resolv_params) else: @@ -784,11 +784,11 @@ class BaseInterface(object): elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: cmds = ['%s del dev %s' % (self.route_cmd, self.iface)] else: - print "No flush command available!" + print("No flush command available!") cmds = [] for cmd in cmds: if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -800,11 +800,11 @@ class BaseInterface(object): """ if not misc.IsValidIP(gw): - print 'WARNING: Invalid gateway found. Aborting!' + print('WARNING: Invalid gateway found. Aborting!') return False cmd = 'route add default gw %s dev %s' % (gw, self.iface) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface("") @@ -845,7 +845,7 @@ class BaseInterface(object): # most. cmd = "ping -q -c 1 %s" % gateway if self.verbose: - print cmd + print(cmd) return misc.LaunchAndWait(cmd) @neediface(False) @@ -860,8 +860,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) @@ -870,7 +870,7 @@ class BaseInterface(object): """ Terminates wpa using wpa_cli""" cmd = 'wpa_cli -i %s terminate' % self.iface if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @@ -942,16 +942,16 @@ 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() elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]: return self._mii_get_plugged_in() else: - print ('Error: No way of checking for a wired connection. Make ' + - 'sure that either mii-tool or ethtool is installed.') + print(('Error: No way of checking for a wired connection. Make ' + + 'sure that either mii-tool or ethtool is installed.')) return False def _eth_get_plugged_in(self): @@ -963,11 +963,11 @@ class BaseWiredInterface(BaseInterface): """ cmd = "%s %s" % (self.ethtool_cmd, self.iface) if not self.IsUp(): - print 'Wired Interface is down, putting it up' + print('Wired Interface is down, putting it up') self.Up() time.sleep(6) if self.verbose: - print cmd + print(cmd) tool_data = misc.Run(cmd, include_stderr=True) if misc.RunRegex( re.compile('(Link detected: yes)', re.I | re.M | re.S), @@ -986,15 +986,15 @@ class BaseWiredInterface(BaseInterface): """ cmd = "%s %s" % (self.miitool_cmd, self.iface) if self.verbose: - print cmd + 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' + print('Wired Interface is down, putting it up') self.Up() time.sleep(4) if self.verbose: - print cmd + print(cmd) tool_data = misc.Run(cmd, include_stderr=True) if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S), @@ -1010,7 +1010,7 @@ class BaseWiredInterface(BaseInterface): os.path.join(wpath.networks, 'wired'), '-Dwired'] if self.verbose: - print cmd + print(cmd) misc.Run(cmd) class BaseWirelessInterface(BaseInterface): @@ -1041,7 +1041,7 @@ class BaseWirelessInterface(BaseInterface): """ cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)] if self.verbose: - print str(cmd) + print(str(cmd)) misc.Run(cmd) @neediface(False) @@ -1068,7 +1068,7 @@ class BaseWirelessInterface(BaseInterface): """ Returns the output of iwconfig for this interface. """ cmd = "iwconfig " + self.iface if self.verbose: - print cmd + print(cmd) return misc.Run(cmd) def _FreqToChannel(self, freq): @@ -1093,7 +1093,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 @@ -1107,7 +1107,7 @@ class BaseWirelessInterface(BaseInterface): """ iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey') if self.verbose: - print iwpriv + print(iwpriv) lines = iwpriv.splitlines()[2:] aps = {} patt = re.compile("((?:[0-9A-Z]{2}:){5}[0-9A-Z]{2})") @@ -1124,7 +1124,7 @@ class BaseWirelessInterface(BaseInterface): bssid = info[3].upper() offset = 0 else: # Invalid - print 'Invalid iwpriv line. Skipping it.' + print('Invalid iwpriv line. Skipping it.') continue ap['nettype'] = info[-1] ap['strength'] = info[1] @@ -1146,11 +1146,11 @@ class BaseWirelessInterface(BaseInterface): elif info[4 + offset] == "NONE": ap['encryption_method'] = None else: - print "Unknown AuthMode, can't assign encryption_method!" + print("Unknown AuthMode, can't assign encryption_method!") ap['encryption_method'] = 'Unknown' aps[bssid] = ap if self.verbose: - print str(aps) + print(str(aps)) return aps def _ParseRalinkAccessPoint(self, ap, ralink_info, cell): @@ -1165,9 +1165,9 @@ class BaseWirelessInterface(BaseInterface): Updated array containing info about the current access point """ - if ralink_info.has_key(ap['bssid']): + if ap['bssid'] in ralink_info: info = ralink_info[ap['bssid']] - for key in info.keys(): + for key in list(info.keys()): ap[key] = info[key] if misc.RunRegex(wep_pattern, cell) == 'on': ap['encryption'] = True @@ -1190,7 +1190,7 @@ class BaseWirelessInterface(BaseInterface): mode = 'managed' cmd = 'iwconfig %s mode %s' % (self.iface, mode) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -1202,12 +1202,12 @@ class BaseWirelessInterface(BaseInterface): """ if not channel.isdigit(): - print 'WARNING: Invalid channel found. Aborting!' + print('WARNING: Invalid channel found. Aborting!') return False cmd = 'iwconfig %s channel %s' % (self.iface, str(channel)) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -1220,7 +1220,7 @@ class BaseWirelessInterface(BaseInterface): """ cmd = 'iwconfig %s key %s' % (self.iface, key) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) @neediface(False) @@ -1257,12 +1257,12 @@ class BaseWirelessInterface(BaseInterface): if channel and str(channel).isdigit(): cmd = "%s channel %s" % (base, str(channel)) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) if bssid: cmd = "%s ap %s" % (base, bssid) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) def GeneratePSK(self, network): @@ -1279,7 +1279,7 @@ class BaseWirelessInterface(BaseInterface): re.I | re.M | re.S) cmd = [wpa_pass_path, str(network['essid']), str(network['key'])] if self.verbose: - print cmd + print(cmd) return misc.RunRegex(key_pattern, misc.Run(cmd)) @neediface(False) @@ -1303,7 +1303,7 @@ class BaseWirelessInterface(BaseInterface): network['bssid'].replace(':', '').lower()), driver] if self.verbose: - print cmd + print(cmd) misc.Run(cmd) def _AuthenticateRalinkLegacy(self, network): @@ -1320,16 +1320,16 @@ class BaseWirelessInterface(BaseInterface): try: info = self._GetRalinkInfo()[network.get('bssid')] except KeyError: - print "Could not find current network in iwpriv " + \ - "get_site_survey results. Cannot authenticate." + print("Could not find current network in iwpriv " + \ + "get_site_survey results. Cannot authenticate.") return if info['enctype'] == "WEP" and info['authtype'] == 'OPEN': - print 'Setting up WEP' + print('Setting up WEP') cmd = ''.join(['iwconfig ', self.iface, ' key ', network.get('key')]) if self.verbose: - print cmd + print(cmd) misc.Run(cmd) else: cmd_list = [] @@ -1344,7 +1344,7 @@ class BaseWirelessInterface(BaseInterface): for cmd in cmd_list: cmd = ['iwpriv', self.iface, 'set', cmd] if self.verbose: - print ' '.join(cmd) + print(' '.join(cmd)) misc.Run(cmd) @neediface([]) @@ -1362,11 +1362,11 @@ class BaseWirelessInterface(BaseInterface): # but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan. essid = misc.Noneify(essid) if essid is not None: - print 'Passing hidden essid to iwlist scan: ' + essid + print('Passing hidden essid to iwlist scan: ' + essid) cmd = cmd + ' essid ' + essid if self.verbose: - print cmd + 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. @@ -1397,7 +1397,7 @@ class BaseWirelessInterface(BaseInterface): or not entry['hidden']): access_points[entry['bssid']] = entry - return access_points.values() + return list(access_points.values()) def _ParseAccessPoint(self, cell, ralink_info): """ Parse a single cell from the output of iwlist. @@ -1416,7 +1416,7 @@ class BaseWirelessInterface(BaseInterface): try: ap['essid'] = misc.to_unicode(ap['essid']) except (UnicodeDecodeError, UnicodeEncodeError): - print 'Unicode problem with current network essid, ignoring!!' + print('Unicode problem with current network essid, ignoring!!') return None # We (well, DBus) don't support ESSIDs with null bytes in it. @@ -1425,7 +1425,7 @@ class BaseWirelessInterface(BaseInterface): ap['essid'] = ap['essid'].replace('\x00', '') if ap['essid'] in ['Hidden', '', "", None]: - print 'hidden' + print('hidden') ap['hidden'] = True ap['essid'] = "" else: @@ -1453,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface): # Mode ap['mode'] = misc.RunRegex(mode_pattern, cell) if ap['mode'] is None: - print 'Invalid network mode string, ignoring!' + print('Invalid network mode string, ignoring!') return None # Break off here if we're using a ralink card @@ -1521,7 +1521,7 @@ class BaseWirelessInterface(BaseInterface): output = misc.Run(cmd) result = misc.RunRegex(auth_pattern, output) if self.verbose: - print 'WPA_CLI RESULT IS', result + print('WPA_CLI RESULT IS', result) if not result: return False @@ -1539,7 +1539,7 @@ class BaseWirelessInterface(BaseInterface): disconnected_time = 0 time.sleep(1) - print 'wpa_supplicant authentication may have failed.' + print('wpa_supplicant authentication may have failed.') return False @@ -1554,7 +1554,7 @@ class BaseWirelessInterface(BaseInterface): time, so we manually speed it up if we see it happening. """ - print 'wpa_supplicant rescan forced...' + print('wpa_supplicant rescan forced...') cmd = 'wpa_cli -i' + self.iface + ' scan' misc.Run(cmd) @@ -1599,7 +1599,7 @@ class BaseWirelessInterface(BaseInterface): if not iwlistauth: cmd = 'iwlist ' + self.iface + ' auth' if self.verbose: - print cmd + print(cmd) output = misc.Run(cmd) else: output = iwlistauth @@ -1614,7 +1614,7 @@ class BaseWirelessInterface(BaseInterface): cmd = 'iwlist ' + self.iface + ' rate' if self.verbose: - print cmd + print(cmd) rates = misc.Run(cmd) # process the output