Permalink
Browse files

Python 3 compatibility

  • Loading branch information...
1 parent 407a2d7 commit 3197d3f75b325d5751871f384b22f92c5cad024e @seveas committed Jun 6, 2012
Showing with 116 additions and 110 deletions.
  1. +18 −13 NetworkManager.py
  2. +2 −2 examples/activate_connection.py
  3. +20 −20 examples/connection_detail.py
  4. +28 −28 examples/info.py
  5. +8 −8 examples/listener.py
  6. +6 −6 examples/openvpn_over_ssh.py
  7. +1 −1 makeconstants.py
  8. +31 −30 n-m
  9. +2 −2 setup.py
View
@@ -1,6 +1,9 @@
import dbus
import sys
+if sys.version_info >= (3,0):
+ basestring = str
+
class NMDbusInterface(object):
bus = dbus.SystemBus()
dbus_service = 'org.freedesktop.NetworkManager'
@@ -13,15 +16,17 @@ def __init__(self, object_path=None):
self.proxy = self.bus.get_object(self.dbus_service, self.object_path)
self.interface = dbus.Interface(self.proxy, self.interface_name)
+ properties = []
try:
properties = self.proxy.GetAll(self.interface_name,
dbus_interface='org.freedesktop.DBus.Properties')
- for p in properties:
- if not hasattr(self.__class__, p):
- setattr(self.__class__, p, self._make_property(p))
- except dbus.exceptions.DBusException, e:
+ except dbus.exceptions.DBusException as e:
if e.get_dbus_name() != 'org.freedesktop.DBus.Error.UnknownMethod':
raise
+ for p in properties:
+ p = str(p)
+ if not hasattr(self.__class__, p):
+ setattr(self.__class__, p, self._make_property(p))
def _make_property(self, name):
def get(self):
@@ -33,10 +38,12 @@ def set(self, value):
return property(get, set)
def unwrap(self, val):
+ if isinstance(val, dbus.ByteArray):
+ return "".join([str(x) for x in val])
if isinstance(val, (dbus.Array, list, tuple)):
return [self.unwrap(x) for x in val]
if isinstance(val, (dbus.Dictionary, dict)):
- return dict([(self.unwrap(x), self.unwrap(y)) for x,y in val.iteritems()])
+ return dict([(self.unwrap(x), self.unwrap(y)) for x,y in val.items()])
if isinstance(val, dbus.ObjectPath):
if val.startswith('/org/freedesktop/NetworkManager/'):
classname = val.split('/')[4]
@@ -45,12 +52,8 @@ def unwrap(self, val):
'Devices': 'Device',
}.get(classname, classname)
return globals()[classname](val)
- if isinstance(val, dbus.ByteArray):
- return "".join([str(x) for x in val])
if isinstance(val, (dbus.Signature, dbus.String)):
return str(val)
- if isinstance(val, dbus.UTF8String):
- return unicode(val)
if isinstance(val, dbus.Boolean):
return bool(val)
if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)):
@@ -62,14 +65,12 @@ def wrap(self, val):
return val.object_path
if hasattr(val, '__iter__') and not isinstance(val, basestring):
if hasattr(val, 'items'):
- return dict([(x, self.wrap(y)) for x, y in val.iteritems()])
+ return dict([(x, self.wrap(y)) for x, y in val.items()])
else:
return [self.wrap(x) for x in val]
return val
def __getattr__(self, name):
- if name == 'object_path':
- print name
try:
return super(NMDbusInterface, self).__getattribute__(name)
except AttributeError:
@@ -148,9 +149,10 @@ class IP6Config(NMDbusInterface):
class VPNConnection(NMDbusInterface):
interface_name = 'org.freedesktop.NetworkManager.VPN.Connection'
+
def const(prefix, val):
prefix = 'NM_' + prefix.upper() + '_'
- for key, vval in globals().iteritems():
+ for key, vval in globals().items():
if 'REASON' in key and 'REASON' not in prefix:
continue
if key.startswith(prefix) and val == vval:
@@ -176,6 +178,8 @@ def const(prefix, val):
NM_DEVICE_TYPE_WIMAX = 7
NM_DEVICE_TYPE_MODEM = 8
NM_DEVICE_TYPE_INFINIBAND = 9
+NM_DEVICE_TYPE_BOND = 10
+NM_DEVICE_TYPE_VLAN = 11
NM_DEVICE_CAP_NONE = 0
NM_DEVICE_CAP_NM_SUPPORTED = 1
NM_DEVICE_CAP_CARRIER_DETECT = 2
@@ -274,6 +278,7 @@ def const(prefix, val):
NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED = 47
NM_DEVICE_STATE_REASON_GSM_SIM_WRONG = 48
NM_DEVICE_STATE_REASON_INFINIBAND_MODE = 49
+NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED = 50
NM_DEVICE_STATE_REASON_LAST = 65535
NM_ACTIVE_CONNECTION_STATE_UNKNOWN = 0
NM_ACTIVE_CONNECTION_STATE_ACTIVATING = 1
@@ -18,7 +18,7 @@
if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed:
break
else:
- print >>sys.stderr, "No active, managed device found"
+ print("No active, managed device found")
sys.exit(1)
else:
dtype = {
@@ -32,7 +32,7 @@
if dev.DeviceType == dtype and dev.State == NetworkManager.NM_DEVICE_STATE_DISCONNECTED:
break
else:
- print >>sys.stderr, "No suitable and available %s device found" % ctype
+ print("No suitable and available %s device found" % ctype)
sys.exit(1)
# And connect
@@ -9,38 +9,38 @@
for conn in NetworkManager.NetworkManager.ActiveConnections:
settings = conn.Connection.GetSettings()
- for s in settings.keys():
+ for s in list(settings.keys()):
if 'data' in settings[s]:
settings[s + '-data'] = settings[s].pop('data')
devices = ""
if conn.Devices:
devices = " (on %s)" % ", ".join([x.Interface for x in conn.Devices])
- print "Active connection: %s%s" % (settings['connection']['id'], devices)
- size = max([max([len(y) for y in x.iterkeys()]) for x in settings.itervalues()])
+ print("Active connection: %s%s" % (settings['connection']['id'], devices))
+ size = max([max([len(y) for y in x.keys()]) for x in settings.values()])
format = " %%-%ds %%s" % (size + 5)
- for key, val in sorted(settings.iteritems()):
- print " %s" % key
- for name, value in val.iteritems():
+ for key, val in sorted(settings.items()):
+ print(" %s" % key)
+ for name, value in val.items():
if name == 'ssid':
value = "".join([str(x) for x in value])
- print format % (name, value)
+ print(format % (name, value))
for dev in conn.Devices:
- print "Device: %s" % dev.Interface
- print " Type %s" % c('device_type', dev.DeviceType)
- # print " IPv4 address %s" % socket.inet_ntoa(struct.pack('L', dev.Ip4Address))
+ print("Device: %s" % dev.Interface)
+ print(" Type %s" % c('device_type', dev.DeviceType))
+ # print(" IPv4 address %s" % socket.inet_ntoa(struct.pack('L', dev.Ip4Address)))
devicedetail = dev.SpecificDevice()
if not callable(devicedetail.HwAddress):
- print " MAC address %s" % devicedetail.HwAddress
- print " IPv4 config"
- print " Addresses"
+ print(" MAC address %s" % devicedetail.HwAddress)
+ print(" IPv4 config")
+ print(" Addresses")
for addr in dev.Ip4Config.Addresses:
- print " %s/%d -> %s" % (socket.inet_ntoa(struct.pack('L', addr[0])), addr[1],
- socket.inet_ntoa(struct.pack('L', addr[2])))
- print " Routes"
+ print(" %s/%d -> %s" % (socket.inet_ntoa(struct.pack('L', addr[0])), addr[1],
+ socket.inet_ntoa(struct.pack('L', addr[2]))))
+ print(" Routes")
for addr in dev.Ip4Config.Routes:
- print " %s/%d -> %s (%d)" % (socket.inet_ntoa(struct.pack('L', route[0])), route[1],
- socket.inet_ntoa(struct.pack('L', route[2])), socket.ntohl(route[3]))
- print " Nameservers"
+ print(" %s/%d -> %s (%d)" % (socket.inet_ntoa(struct.pack('L', route[0])), route[1],
+ socket.inet_ntoa(struct.pack('L', route[2])), socket.ntohl(route[3])))
+ print(" Nameservers")
for ns in dev.Ip4Config.Nameservers:
- print " %s" % socket.inet_ntoa(struct.pack('L', ns))
+ print(" %s" % socket.inet_ntoa(struct.pack('L', ns)))
View
@@ -6,43 +6,43 @@
import NetworkManager
c = NetworkManager.const
-print "%-30s %s" % ("Version:", NetworkManager.NetworkManager.Version)
-print "%-30s %s" % ("Hostname:", NetworkManager.Settings.Hostname)
-print "%-30s %s" % ("Can modify:", NetworkManager.Settings.CanModify)
-print "%-30s %s" % ("Networking enabled:", NetworkManager.NetworkManager.NetworkingEnabled)
-print "%-30s %s" % ("Wireless enabled:", NetworkManager.NetworkManager.WirelessEnabled)
-print "%-30s %s" % ("Wireless hw enabled:", NetworkManager.NetworkManager.WirelessHardwareEnabled)
-print "%-30s %s" % ("Wwan enabled:", NetworkManager.NetworkManager.WwanEnabled)
-print "%-30s %s" % ("Wwan hw enabled:", NetworkManager.NetworkManager.WwanHardwareEnabled)
-print "%-30s %s" % ("Wimax enabled:", NetworkManager.NetworkManager.WimaxEnabled)
-print "%-30s %s" % ("Wimax hw enabled:", NetworkManager.NetworkManager.WimaxHardwareEnabled)
-print "%-30s %s" % ("Overall state:", c('state', NetworkManager.NetworkManager.State))
-
-print ""
-
-print "Permissions"
+print("%-30s %s" % ("Version:", NetworkManager.NetworkManager.Version))
+print("%-30s %s" % ("Hostname:", NetworkManager.Settings.Hostname))
+print("%-30s %s" % ("Can modify:", NetworkManager.Settings.CanModify))
+print("%-30s %s" % ("Networking enabled:", NetworkManager.NetworkManager.NetworkingEnabled))
+print("%-30s %s" % ("Wireless enabled:", NetworkManager.NetworkManager.WirelessEnabled))
+print("%-30s %s" % ("Wireless hw enabled:", NetworkManager.NetworkManager.WirelessHardwareEnabled))
+print("%-30s %s" % ("Wwan enabled:", NetworkManager.NetworkManager.WwanEnabled))
+print("%-30s %s" % ("Wwan hw enabled:", NetworkManager.NetworkManager.WwanHardwareEnabled))
+print("%-30s %s" % ("Wimax enabled:", NetworkManager.NetworkManager.WimaxEnabled))
+print("%-30s %s" % ("Wimax hw enabled:", NetworkManager.NetworkManager.WimaxHardwareEnabled))
+print("%-30s %s" % ("Overall state:", c('state', NetworkManager.NetworkManager.State)))
+
+print("")
+
+print("Permissions")
for perm, val in sorted(NetworkManager.NetworkManager.GetPermissions().items()):
- print "%-30s %s" % (perm[31:] + ':', val)
+ print("%-30s %s" % (perm[31:] + ':', val))
-print ""
+print("")
-print "Available network devices"
-print "%-10s %-19s %-20s %s" % ("Name", "State", "Driver", "Managed?")
+print("Available network devices")
+print("%-10s %-19s %-20s %s" % ("Name", "State", "Driver", "Managed?"))
for dev in NetworkManager.NetworkManager.GetDevices():
- print "%-10s %-19s %-20s %s" % (dev.Interface, c('device_state', dev.State), dev.Driver, dev.Managed)
+ print("%-10s %-19s %-20s %s" % (dev.Interface, c('device_state', dev.State), dev.Driver, dev.Managed))
-print ""
+print("")
-print "Available connections"
-print "%-30s %s" % ("Name", "Type")
+print("Available connections")
+print("%-30s %s" % ("Name", "Type"))
for conn in NetworkManager.Settings.ListConnections():
settings = conn.GetSettings()['connection']
- print "%-30s %s" % (settings['id'], settings['type'])
+ print("%-30s %s" % (settings['id'], settings['type']))
-print ""
+print("")
-print "Active connections"
-print "%-30s %-20s %-10s %s" % ("Name", "Type", "Default", "Devices")
+print("Active connections")
+print("%-30s %-20s %-10s %s" % ("Name", "Type", "Default", "Devices"))
for conn in NetworkManager.NetworkManager.ActiveConnections:
settings = conn.Connection.GetSettings()['connection']
- print "%-30s %-20s %-10s %s" % (settings['id'], settings['type'], conn.Default, ", ".join([x.Interface for x in conn.Devices]))
+ print("%-30s %-20s %-10s %s" % (settings['id'], settings['type'], conn.Default, ", ".join([x.Interface for x in conn.Devices])))
View
@@ -3,7 +3,7 @@
"""
import dbus.mainloop.glib; dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
-import gobject
+from gi.repository import GObject
import NetworkManager
d_args = ('sender', 'destination', 'interface', 'member', 'path')
@@ -16,17 +16,17 @@ def main():
NetworkManager.NetworkManager.connect_to_signal('DeviceAdded', display_sig, **d_args)
NetworkManager.NetworkManager.connect_to_signal('DeviceRemoved', display_sig, **d_args)
- print "Waiting for signals"
- print "-------------------"
+ print("Waiting for signals")
+ print("-------------------")
- loop = gobject.MainLoop()
+ loop = GObject.MainLoop()
loop.run()
def display_sig(*args, **kwargs):
- print "Received signal: %s.%s" % (kwargs['d_interface'], kwargs['d_member'])
- print "Sender: (%s)%s" % (kwargs['d_sender'], kwargs['d_path'])
- print "Arguments: (%s)" % ", ".join([str(x) for x in args])
- print "-------------------"
+ print("Received signal: %s.%s" % (kwargs['d_interface'], kwargs['d_member']))
+ print("Sender: (%s)%s" % (kwargs['d_sender'], kwargs['d_path']))
+ print("Arguments: (%s)" % ", ".join([str(x) for x in args]))
+ print("-------------------")
if __name__ == '__main__':
main()
@@ -24,9 +24,9 @@
sock.connect(('localhost', LOCALPORT))
except socket.error:
# Set up the SSH tunnel if it isn't
- print "Connecting to " + SSH_HOST
+ print("Connecting to " + SSH_HOST)
if subprocess.call([SSH, '-L%s:%s' % (LOCALPORT, VPN_HOST), '-f', '-n', '-N', SSH_HOST]) != 0:
- print >>sys.stderr, "SSH to %s failed" % SSH_HOST
+ print("SSH to %s failed" % SSH_HOST)
sys.exit(1)
for conn in NetworkManager.Settings.ListConnections():
@@ -37,23 +37,23 @@
uuid = settings['connection']['uuid']
break
else:
- print >>sys.stderr, "VPN with name %s not found" % VPN_NAME
+ print("VPN with name %s not found" % VPN_NAME)
sys.exit(1)
# Bail out of another vpn is active
for conn in NetworkManager.NetworkManager.ActiveConnections:
if conn.Vpn:
vid = conn.Connection.GetSettings()['connection']['id']
- print >>sys.stderr, "The vpn %s is already active" % vid
+ print("The vpn %s is already active" % vid)
sys.exit(1)
# Activate VPN
for dev in NetworkManager.NetworkManager.GetDevices():
if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed:
break
else:
- print >>sys.stderr, "No active, managed device found"
+ print("No active, managed device found")
sys.exit(1)
-print "Activating VPN"
+print("Activating VPN")
NetworkManager.NetworkManager.ActivateConnection(vpn, dev, "/")
View
@@ -20,6 +20,6 @@
else:
val = last + 1
key = key.strip()
- print '%s = %d' % (key, val)
+ print('%s = %d' % (key, val))
last = val
Oops, something went wrong.

0 comments on commit 3197d3f

Please sign in to comment.