[PATCH 1/1] Make python2.6-3.3 compatible and pep8 compliant.
Antoni Segura Puimedon
asegurap at redhat.com
Thu Nov 14 14:52:39 UTC 2013
Updated python code to be compatible with Python 2.6, 2.7 and 3.3
Done the same for the C code.
TODO: Move test_ethtool.py to python-nose (that has python2 and 3
support).
Signed-off-by: Antoni S. Puimedon <asegurap at redhat.com>
---
pethtool.py | 625 ++++++++++++++++++------------------
pifconfig.py | 142 ++++----
python-ethtool/etherinfo.h | 17 +
python-ethtool/etherinfo_ipv6_obj.c | 15 +-
python-ethtool/etherinfo_obj.c | 21 +-
python-ethtool/etherinfo_struct.h | 4 +
python-ethtool/ethtool.c | 46 ++-
setup.py | 39 ++-
tests/test_ethtool.py | 2 +-
9 files changed, 497 insertions(+), 414 deletions(-)
diff --git a/pethtool.py b/pethtool.py
index bdd21a4..7345fc8 100755
--- a/pethtool.py
+++ b/pethtool.py
@@ -1,7 +1,7 @@
#! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
-# Copyright (C) 2008 Red Hat Inc.
+# Copyright (C) 2008-2013 Red Hat Inc.
#
# This application is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
@@ -11,15 +11,20 @@
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
+from __future__ import print_function
+
+import ethtool
+import getopt
+import sys
-import getopt, ethtool, sys
def usage():
- print '''Usage: pethtool [OPTIONS] [<interface>]
- -h|--help Give this help list
- -c|--show-coalesce Show coalesce options
- -C|--coalesce Set coalesce options
- [adaptive-rx on|off]
+ """Prints the cli usage info."""
+ print('''Usage: pethtool [OPTIONS] [<interface>]
+ -h|--help Give this help list
+ -c|--show-coalesce Show coalesce options
+ -C|--coalesce Set coalesce options
+ [adaptive-rx on|off]
[adaptive-tx on|off]
[rx-usecs N]
[rx-frames N]
@@ -40,341 +45,335 @@ def usage():
[rx-frames-high N]
[tx-usecs-high N]
[tx-frames-high N]
- [sample-interval N]
- -i|--driver Show driver information
- -k|--show-offload Get protocol offload information
- -K|--offload Set protocol offload
- [ tso on|off ]'''
+ [sample-interval N]
+ -i|--driver Show driver information
+ -k|--show-offload Get protocol offload information
+ -K|--offload Set protocol offload
+ [ tso on|off ]''')
+
+TAB = ""
-tab = ""
def printtab(msg):
- print tab + msg
+ print(TAB + msg)
+
all_devices = []
+
ethtool_coalesce_msgs = (
- ( "stats-block-usecs",
- "stats_block_coalesce_usecs" ),
- ( "sample-interval",
- "rate_sample_interval" ),
- ( "pkt-rate-low",
- "pkt_rate_low"),
- ( "pkt-rate-high",
- "pkt_rate_high"),
- ( "\n" ),
- ( "rx-usecs",
- "rx_coalesce_usecs"),
- ( "rx-frames",
- "rx_max_coalesced_frames"),
- ( "rx-usecs-irq",
- "rx_coalesce_usecs_irq"),
- ( "rx-frames-irq",
- "rx_max_coalesced_frames_irq"),
- ( "\n" ),
- ( "tx-usecs",
- "tx_coalesce_usecs"),
- ( "tx-frames",
- "tx_max_coalesced_frames"),
- ( "tx-usecs-irq",
- "tx_coalesce_usecs_irq"),
- ( "tx-frames-irq",
- "tx_max_coalesced_frames_irq"),
- ( "\n" ),
- ( "rx-usecs-low",
- "rx_coalesce_usecs_low"),
- ( "rx-frame-low",
- "rx_max_coalesced_frames_low"),
- ( "tx-usecs-low",
- "tx_coalesce_usecs_low"),
- ( "tx-frame-low",
- "tx_max_coalesced_frames_low"),
- ( "\n" ),
- ( "rx-usecs-high",
- "rx_coalesce_usecs_high"),
- ( "rx-frame-high",
- "rx_max_coalesced_frames_high"),
- ( "tx-usecs-high",
- "tx_coalesce_usecs_high"),
- ( "tx-frame-high",
- "tx_max_coalesced_frames_high"),
+ ("stats-block-usecs", "stats_block_coalesce_usecs"),
+ ("sample-interval", "rate_sample_interval"),
+ ("pkt-rate-low", "pkt_rate_low"),
+ ("pkt-rate-high", "pkt_rate_high"),
+ ("\n"),
+ ("rx-usecs", "rx_coalesce_usecs"),
+ ("rx-frames", "rx_max_coalesced_frames"),
+ ("rx-usecs-irq", "rx_coalesce_usecs_irq"),
+ ("rx-frames-irq", "rx_max_coalesced_frames_irq"),
+ ("\n"),
+ ("tx-usecs", "tx_coalesce_usecs"),
+ ("tx-frames", "tx_max_coalesced_frames"),
+ ("tx-usecs-irq", "tx_coalesce_usecs_irq"),
+ ("tx-frames-irq", "tx_max_coalesced_frames_irq"),
+ ("\n"),
+ ("rx-usecs-low", "rx_coalesce_usecs_low"),
+ ("rx-frame-low", "rx_max_coalesced_frames_low"),
+ ("tx-usecs-low", "tx_coalesce_usecs_low"),
+ ("tx-frame-low", "tx_max_coalesced_frames_low"),
+ ("\n"),
+ ("rx-usecs-high", "rx_coalesce_usecs_high"),
+ ("rx-frame-high", "rx_max_coalesced_frames_high"),
+ ("tx-usecs-high", "tx_coalesce_usecs_high"),
+ ("tx-frame-high", "tx_max_coalesced_frames_high"),
)
+
def get_coalesce_dict_entry(ethtool_name):
- if ethtool_name == "adaptive-rx":
- return "use_adaptive_rx_coalesce"
-
- if ethtool_name == "adaptive-tx":
- return "use_adaptive_tx_coalesce"
-
- for name in ethtool_coalesce_msgs:
- if name[0] == ethtool_name:
- return name[1]
-
- return None
-
-def show_coalesce(interface, args = None):
- printtab("Coalesce parameters for %s:" % interface)
- try:
- coal = ethtool.get_coalesce(interface)
- except IOError:
- printtab(" NOT supported!")
- return
-
- printtab("Adaptive RX: %s TX: %s" % (coal["use_adaptive_rx_coalesce"] and "on" or "off",
- coal["use_adaptive_tx_coalesce"] and "on" or "off"))
-
- printed = [ "use_adaptive_rx_coalesce",
- "use_adaptive_tx_coalesce" ]
- for tunable in ethtool_coalesce_msgs:
- if tunable[0] == '\n':
- print
- else:
- printtab("%s: %s" % (tunable[0], coal[tunable[1]]))
- printed.append(tunable[1])
-
- coalkeys = coal.keys()
- if len(coalkeys) != len(printed):
- print
- for tunable in coalkeys:
- if tunable not in printed:
- printtab("%s %s" % (tunable, coal[tunable]))
-
+ if ethtool_name == "adaptive-rx":
+ return "use_adaptive_rx_coalesce"
+
+ if ethtool_name == "adaptive-tx":
+ return "use_adaptive_tx_coalesce"
+
+ for name in ethtool_coalesce_msgs:
+ if name[0] == ethtool_name:
+ return name[1]
+
+ return None
+
+
+def show_coalesce(interface, args=None):
+ printtab("Coalesce parameters for %s:" % interface)
+ try:
+ coal = ethtool.get_coalesce(interface)
+ except IOError:
+ printtab(" NOT supported!")
+ return
+
+ printtab("Adaptive RX: %s TX: %s" %
+ (coal["use_adaptive_rx_coalesce"] and "on" or "off",
+ coal["use_adaptive_tx_coalesce"] and "on" or "off"))
+
+ printed = ["use_adaptive_rx_coalesce", "use_adaptive_tx_coalesce"]
+ for tunable in ethtool_coalesce_msgs:
+ if tunable[0] == '\n':
+ print()
+ else:
+ printtab("%s: %s" % (tunable[0], coal[tunable[1]]))
+ printed.append(tunable[1])
+
+ coalkeys = coal.keys()
+ if len(coalkeys) != len(printed):
+ print()
+ for tunable in coalkeys:
+ if tunable not in printed:
+ printtab("%s %s" % (tunable, coal[tunable]))
+
+
def set_coalesce(interface, args):
- try:
- coal = ethtool.get_coalesce(interface)
- except IOError:
- printtab("Interrupt coalescing NOT supported on %s!" % interface)
- return
-
- changed = False
- args = [a.lower() for a in args]
- for arg, value in [ ( args[i], args[i + 1] ) for i in range(0, len(args), 2) ]:
- real_arg = get_coalesce_dict_entry(arg)
- if not real_arg:
- continue
- if value == "on":
- value = 1
- elif value == "off":
- value = 0
- else:
- try:
- value = int(value)
- except:
- continue
- if coal[real_arg] != value:
- coal[real_arg] = value
- changed = True
-
- if not changed:
- return
-
- ethtool.set_coalesce(interface, coal)
-
-def show_offload(interface, args = None):
- try:
- sg = ethtool.get_sg(interface) and "on" or "off"
- except IOError:
- sg = "not supported"
-
- try:
- tso = ethtool.get_tso(interface) and "on" or "off"
- except IOError:
- tso = "not supported"
-
- try:
- ufo = ethtool.get_ufo(interface) and "on" or "off"
- except IOError:
- ufo = "not supported"
-
- try:
- gso = ethtool.get_gso(interface) and "on" or "off"
- except IOError:
- gso = "not supported"
-
- printtab("scatter-gather: %s" % sg)
- printtab("tcp segmentation offload: %s" % tso)
- printtab("udp fragmentation offload: %s" % ufo)
- printtab("generic segmentation offload: %s" % gso)
+ try:
+ coal = ethtool.get_coalesce(interface)
+ except IOError:
+ printtab("Interrupt coalescing NOT supported on %s!" % interface)
+ return
+
+ changed = False
+ args = [a.lower() for a in args]
+ for arg, value in [(args[i], args[i + 1]) for i in range(0, len(args), 2)]:
+ real_arg = get_coalesce_dict_entry(arg)
+ if not real_arg:
+ continue
+ if value == "on":
+ value = 1
+ elif value == "off":
+ value = 0
+ else:
+ try:
+ value = int(value)
+ except:
+ continue
+ if coal[real_arg] != value:
+ coal[real_arg] = value
+ changed = True
+
+ if not changed:
+ return
+
+ ethtool.set_coalesce(interface, coal)
+
+
+def show_offload(interface, args=None):
+ try:
+ sg = ethtool.get_sg(interface) and "on" or "off"
+ except IOError:
+ sg = "not supported"
+
+ try:
+ tso = ethtool.get_tso(interface) and "on" or "off"
+ except IOError:
+ tso = "not supported"
+
+ try:
+ ufo = ethtool.get_ufo(interface) and "on" or "off"
+ except IOError:
+ ufo = "not supported"
+
+ try:
+ gso = ethtool.get_gso(interface) and "on" or "off"
+ except IOError:
+ gso = "not supported"
+
+ printtab("scatter-gather: %s" % sg)
+ printtab("tcp segmentation offload: %s" % tso)
+ printtab("udp fragmentation offload: %s" % ufo)
+ printtab("generic segmentation offload: %s" % gso)
+
def set_offload(interface, args):
- cmd, value = [a.lower() for a in args]
+ cmd, value = [a.lower() for a in args]
- if cmd == "tso":
- value = value == "on" and 1 or 0
- try:
- ethtool.set_tso(interface, value)
- except:
- pass
+ if cmd == "tso":
+ value = value == "on" and 1 or 0
+ try:
+ ethtool.set_tso(interface, value)
+ except:
+ pass
ethtool_ringparam_msgs = (
- ( "Pre-set maximums", ),
- ( "RX:\t\t", "rx_max_pending" ),
- ( "RX Mini:\t", "rx_mini_max_pending" ),
- ( "RX Jumbo:\t", "rx_jumbo_max_pending" ),
- ( "TX:\t\t", "tx_max_pending" ),
- ( "Current hardware settings", ),
- ( "RX:\t\t", "rx_pending" ),
- ( "RX Mini:\t", "rx_mini_pending" ),
- ( "RX Jumbo:\t", "rx_jumbo_pending" ),
- ( "TX:\t\t", "tx_pending" ),
+ ("Pre-set maximums",),
+ ("RX:\t\t", "rx_max_pending"),
+ ("RX Mini:\t", "rx_mini_max_pending"),
+ ("RX Jumbo:\t", "rx_jumbo_max_pending"),
+ ("TX:\t\t", "tx_max_pending"),
+ ("Current hardware settings",),
+ ("RX:\t\t", "rx_pending"),
+ ("RX Mini:\t", "rx_mini_pending"),
+ ("RX Jumbo:\t", "rx_jumbo_pending"),
+ ("TX:\t\t", "tx_pending"),
)
-def show_ring(interface, args = None):
- printtab("Ring parameters for %s:" % interface)
- try:
- ring = ethtool.get_ringparam(interface)
- except IOError:
- printtab(" NOT supported!")
- return
-
- printed = []
- for tunable in ethtool_ringparam_msgs:
- if len(tunable) == 1:
- printtab("%s:" % tunable[0])
- else:
- printtab("%s %s" % (tunable[0], ring[tunable[1]]))
- printed.append(tunable[1])
-
- ringkeys = ring.keys()
- if len(ringkeys) != len(printed):
- print
- for tunable in ringkeys:
- if tunable not in printed:
- printtab("%s %s" % (tunable, ring[tunable]))
+
+def show_ring(interface, args=None):
+ printtab("Ring parameters for %s:" % interface)
+ try:
+ ring = ethtool.get_ringparam(interface)
+ except IOError:
+ printtab(" NOT supported!")
+ return
+
+ printed = []
+ for tunable in ethtool_ringparam_msgs:
+ if len(tunable) == 1:
+ printtab("%s:" % tunable[0])
+ else:
+ printtab("%s %s" % (tunable[0], ring[tunable[1]]))
+ printed.append(tunable[1])
+
+ ringkeys = ring.keys()
+ if len(ringkeys) != len(printed):
+ print()
+ for tunable in ringkeys:
+ if tunable not in printed:
+ printtab("%s %s" % (tunable, ring[tunable]))
ethtool_ringparam_map = {
- "rx": "rx_pending",
- "rx-mini": "rx_mini_pending",
- "rx-jumbo": "rx_jumbo_pending",
- "tx": "tx_pending",
+ "rx": "rx_pending",
+ "rx-mini": "rx_mini_pending",
+ "rx-jumbo": "rx_jumbo_pending",
+ "tx": "tx_pending",
}
+
def set_ringparam(interface, args):
- try:
- ring = ethtool.get_ringparam(interface)
- except IOError:
- printtab("ring parameters NOT supported on %s!" % interface)
- return
-
- changed = False
- args = [a.lower() for a in args]
- for arg, value in [ ( args[i], args[i + 1] ) for i in range(0, len(args), 2) ]:
- if not ethtool_ringparam_map.has_key(arg):
- continue
- try:
- value = int(value)
- except:
- continue
- real_arg = ethtool_ringparam_map[arg]
- if ring[real_arg] != value:
- ring[real_arg] = value
- changed = True
-
- if not changed:
- return
-
- ethtool.set_ringparam(interface, ring)
-
-def show_driver(interface, args = None):
- try:
- driver = ethtool.get_module(interface)
- except IOError:
- driver = "not implemented"
-
- try:
- bus = ethtool.get_businfo(interface)
- except IOError:
- bus = "not available"
-
- printtab("driver: %s" % driver)
- printtab("bus-info: %s" % bus)
+ try:
+ ring = ethtool.get_ringparam(interface)
+ except IOError:
+ printtab("ring parameters NOT supported on %s!" % interface)
+ return
+
+ changed = False
+ args = [a.lower() for a in args]
+ for arg, value in [(args[i], args[i + 1]) for i in range(0, len(args), 2)]:
+ if arg not in ethtool_ringparam_map:
+ continue
+ try:
+ value = int(value)
+ except:
+ continue
+ real_arg = ethtool_ringparam_map[arg]
+ if ring[real_arg] != value:
+ ring[real_arg] = value
+ changed = True
+
+ if not changed:
+ return
+
+ ethtool.set_ringparam(interface, ring)
+
+
+def show_driver(interface, args=None):
+ try:
+ driver = ethtool.get_module(interface)
+ except IOError:
+ driver = "not implemented"
+
+ try:
+ bus = ethtool.get_businfo(interface)
+ except IOError:
+ bus = "not available"
+
+ printtab("driver: %s" % driver)
+ printtab("bus-info: %s" % bus)
+
def run_cmd(cmd, interface, args):
- global tab, all_devices
-
- active_devices = ethtool.get_active_devices()
- if not interface:
- tab = " "
- for interface in all_devices:
- inactive = " (not active)"
- if interface in active_devices:
- inactive = ""
- print "%s%s:" % (interface, inactive)
- cmd(interface, args)
- else:
- cmd(interface, args)
+ global tab, all_devices
+
+ active_devices = ethtool.get_active_devices()
+ if not interface:
+ tab = " "
+ for interface in all_devices:
+ inactive = " (not active)"
+ if interface in active_devices:
+ inactive = ""
+ print("%s%s:" % (interface, inactive))
+ cmd(interface, args)
+ else:
+ cmd(interface, args)
+
def run_cmd_noargs(cmd, args):
- if args:
- run_cmd(cmd, args[0], None)
- else:
- global all_devices
- all_devices = ethtool.get_devices()
- run_cmd(cmd, None, None)
+ if args:
+ run_cmd(cmd, args[0], None)
+ else:
+ global all_devices
+ all_devices = ethtool.get_devices()
+ run_cmd(cmd, None, None)
+
def main():
- global all_devices
-
- try:
- opts, args = getopt.getopt(sys.argv[1:],
- "hcCgGikK",
- ("help",
- "show-coalesce",
- "coalesce",
- "show-ring",
- "set-ring",
- "driver",
- "show-offload",
- "offload"))
- except getopt.GetoptError, err:
- usage()
- print str(err)
- sys.exit(2)
-
- if not opts:
- usage()
- sys.exit(0)
-
- for o, a in opts:
- if o in ("-h", "--help"):
- usage()
- return
- elif o in ("-c", "--show-coalesce"):
- run_cmd_noargs(show_coalesce, args)
- break
- elif o in ("-i", "--driver"):
- run_cmd_noargs(show_driver, args)
- break
- elif o in ("-k", "--show-offload"):
- run_cmd_noargs(show_offload, args)
- break
- elif o in ("-g", "--show-ring"):
- run_cmd_noargs(show_ring, args)
- break
- elif o in ("-K", "--offload",
- "-C", "--coalesce",
- "-G", "--set-ring"):
- all_devices = ethtool.get_devices()
- if len(args) < 2:
- usage()
- sys.exit(1)
-
- if args[0] not in all_devices:
- interface = None
- else:
- interface = args[0]
- args = args[1:]
-
- if o in ("-K", "--offload"):
- cmd = set_offload
- elif o in ("-C", "--coalesce"):
- cmd = set_coalesce
- elif o in ("-G", "--set-ring"):
- cmd = set_ringparam
-
- run_cmd(cmd, interface, args)
- break
+ global all_devices
+
+ try:
+ opts, args = getopt.getopt(sys.argv[1:],
+ "hcCgGikK",
+ ("help",
+ "show-coalesce",
+ "coalesce",
+ "show-ring",
+ "set-ring",
+ "driver",
+ "show-offload",
+ "offload"))
+ except getopt.GetoptError as err:
+ usage()
+ print(str(err))
+ sys.exit(2)
+
+ if not opts:
+ usage()
+ sys.exit(0)
+
+ for o, _ in opts:
+ if o in ("-h", "--help"):
+ usage()
+ return
+ elif o in ("-c", "--show-coalesce"):
+ run_cmd_noargs(show_coalesce, args)
+ break
+ elif o in ("-i", "--driver"):
+ run_cmd_noargs(show_driver, args)
+ break
+ elif o in ("-k", "--show-offload"):
+ run_cmd_noargs(show_offload, args)
+ break
+ elif o in ("-g", "--show-ring"):
+ run_cmd_noargs(show_ring, args)
+ break
+ elif o in ("-K", "--offload",
+ "-C", "--coalesce",
+ "-G", "--set-ring"):
+ all_devices = ethtool.get_devices()
+ if len(args) < 2:
+ usage()
+ sys.exit(1)
+
+ if args[0] not in all_devices:
+ interface = None
+ else:
+ interface = args[0]
+ args = args[1:]
+
+ if o in ("-K", "--offload"):
+ cmd = set_offload
+ elif o in ("-C", "--coalesce"):
+ cmd = set_coalesce
+ elif o in ("-G", "--set-ring"):
+ cmd = set_ringparam
+
+ run_cmd(cmd, interface, args)
+ break
if __name__ == '__main__':
main()
diff --git a/pifconfig.py b/pifconfig.py
index 1536071..fd70b59 100755
--- a/pifconfig.py
+++ b/pifconfig.py
@@ -1,7 +1,7 @@
#! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
-# Copyright (C) 2008 Red Hat Inc.
+# Copyright (C) 2008-13 Red Hat Inc.
#
# Arnaldo Carvalho de Melo <acme at redhat.com>
#
@@ -13,86 +13,88 @@
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
+from __future__ import print_function
-import getopt, ethtool, sys
from optparse import OptionParser
+import ethtool
+import sys
+
def flags2str(flags):
- string = ""
- if flags & ethtool.IFF_UP:
- string += "UP "
- if flags & ethtool.IFF_BROADCAST:
- string += "BROADCAST "
- if flags & ethtool.IFF_DEBUG:
- string += "DEBUG "
- if flags & ethtool.IFF_LOOPBACK:
- string += "LOOPBACK "
- if flags & ethtool.IFF_POINTOPOINT:
- string += "POINTOPOINT "
- if flags & ethtool.IFF_NOTRAILERS:
- string += "NOTRAILERS "
- if flags & ethtool.IFF_RUNNING:
- string += "RUNNING "
- if flags & ethtool.IFF_NOARP:
- string += "NOARP "
- if flags & ethtool.IFF_PROMISC:
- string += "PROMISC "
- if flags & ethtool.IFF_ALLMULTI:
- string += "ALLMULTI "
- if flags & ethtool.IFF_MASTER:
- string += "MASTER "
- if flags & ethtool.IFF_SLAVE:
- string += "SLAVE "
- if flags & ethtool.IFF_MULTICAST:
- string += "MULTICAST "
- if flags & ethtool.IFF_PORTSEL:
- string += "PORTSEL "
- if flags & ethtool.IFF_AUTOMEDIA:
- string += "AUTOMEDIA "
- if flags & ethtool.IFF_DYNAMIC:
- string += "DYNAMIC "
+ """Returns a string representation of ethtool flags."""
+ string = ""
+ if flags & ethtool.IFF_UP:
+ string += "UP "
+ if flags & ethtool.IFF_BROADCAST:
+ string += "BROADCAST "
+ if flags & ethtool.IFF_DEBUG:
+ string += "DEBUG "
+ if flags & ethtool.IFF_LOOPBACK:
+ string += "LOOPBACK "
+ if flags & ethtool.IFF_POINTOPOINT:
+ string += "POINTOPOINT "
+ if flags & ethtool.IFF_NOTRAILERS:
+ string += "NOTRAILERS "
+ if flags & ethtool.IFF_RUNNING:
+ string += "RUNNING "
+ if flags & ethtool.IFF_NOARP:
+ string += "NOARP "
+ if flags & ethtool.IFF_PROMISC:
+ string += "PROMISC "
+ if flags & ethtool.IFF_ALLMULTI:
+ string += "ALLMULTI "
+ if flags & ethtool.IFF_MASTER:
+ string += "MASTER "
+ if flags & ethtool.IFF_SLAVE:
+ string += "SLAVE "
+ if flags & ethtool.IFF_MULTICAST:
+ string += "MULTICAST "
+ if flags & ethtool.IFF_PORTSEL:
+ string += "PORTSEL "
+ if flags & ethtool.IFF_AUTOMEDIA:
+ string += "AUTOMEDIA "
+ if flags & ethtool.IFF_DYNAMIC:
+ string += "DYNAMIC "
+
+ return string.strip()
- return string.strip()
def show_config(device):
- ipaddr = ethtool.get_ipaddr(device)
- netmask = ethtool.get_netmask(device)
- flags = ethtool.get_flags(device)
- print '%-9.9s' % device,
- if not (flags & ethtool.IFF_LOOPBACK):
- print "HWaddr %s" % ethtool.get_hwaddr(device),
- print '''
- inet addr:%s''' % ipaddr,
- if not (flags & (ethtool.IFF_LOOPBACK | ethtool.IFF_POINTOPOINT)):
- print "Bcast:%s" % ethtool.get_broadcast(device),
- print ' Mask:%s' % netmask
- for info in ethtool.get_interfaces_info(device):
- for addr in info.get_ipv6_addresses():
- print (" inet6 addr: %s/%s Scope: %s"
- % (addr.address,
- addr.netmask,
- addr.scope))
- print ' %s' % flags2str(flags)
- print
+ """Prints the configuration of a device."""
+ ipaddr = ethtool.get_ipaddr(device)
+ netmask = ethtool.get_netmask(device)
+ flags = ethtool.get_flags(device)
+ print('%-9.9s' % device, end=' ')
+ if not (flags & ethtool.IFF_LOOPBACK):
+ print("HWaddr %s" % ethtool.get_hwaddr(device), end=' ')
+ print('''
+ inet addr:%s''' % ipaddr, end=' ')
+ if not (flags & (ethtool.IFF_LOOPBACK | ethtool.IFF_POINTOPOINT)):
+ print("Bcast:%s" % ethtool.get_broadcast(device), end=' ')
+ print(' Mask:%s' % netmask)
+ for info in ethtool.get_interfaces_info(device):
+ for addr in info.get_ipv6_addresses():
+ print(" inet6 addr: %s/%s Scope: %s" %
+ (addr.address, addr.netmask, addr.scope))
+ print(' %s' % flags2str(flags), end='\n\n')
-def main():
- global all_devices
- usage="usage: %prog [interface [interface [interface] ...]]"
- parser = OptionParser(usage=usage)
- (opts, args) = parser.parse_args()
+def main():
+ usage = "usage: %prog [interface [interface [interface] ...]]"
+ parser = OptionParser(usage=usage)
+ _, args = parser.parse_args()
- if args is None or len(args) == 0:
- sel_devs = ethtool.get_active_devices()
- else:
- sel_devs = args
+ if args is None or len(args) == 0:
+ sel_devs = ethtool.get_active_devices()
+ else:
+ sel_devs = args
- for device in sel_devs:
- try:
- show_config(device)
- except Exception, ex:
- print "** ERROR ** [Device %s]: %s" % (device, str(ex))
- sys.exit(2)
+ for device in sel_devs:
+ try:
+ show_config(device)
+ except Exception as ex:
+ print("** ERROR ** [Device %s]: %s" % (device, str(ex)))
+ sys.exit(2)
if __name__ == '__main__':
main()
diff --git a/python-ethtool/etherinfo.h b/python-ethtool/etherinfo.h
index 5e1056a..820a381 100644
--- a/python-ethtool/etherinfo.h
+++ b/python-ethtool/etherinfo.h
@@ -35,4 +35,21 @@ void free_ipv6addresses(struct ipv6address *ptr);
int open_netlink(struct etherinfo_obj_data *);
void close_netlink(struct etherinfo_obj_data *);
+#if PY_MAJOR_VERSION >= 3
+#define PyString_FromString PyUnicode_FromString
+#define PyString_Check PyUnicode_Check
+#define PyString_AsString(obj) \
+ PyBytes_AsString(PyUnicode_AsASCIIString(obj))
+#define PyString_FromFormat PyUnicode_FromFormat
+#define PyString_Concat(left, right) \
+ do {register PyObject *temp; \
+ temp = PyUnicode_Concat(*left, right); \
+ Py_DECREF(*left); \
+ *left = temp;} \
+ while(0)
+#define PyString_ConcatAndDel(left, right) \
+ PyString_Concat(left, right); \
+ Py_XDECREF(right)
+#endif
+
#endif
diff --git a/python-ethtool/etherinfo_ipv6_obj.c b/python-ethtool/etherinfo_ipv6_obj.c
index fb751d4..9722624 100644
--- a/python-ethtool/etherinfo_ipv6_obj.c
+++ b/python-ethtool/etherinfo_ipv6_obj.c
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2010 Red Hat Inc.
+ * Copyright (C) 2009-2013 Red Hat Inc.
*
* David Sommerseth <davids at redhat.com>
*
@@ -40,7 +40,7 @@ void _ethtool_etherinfo_ipv6_dealloc(etherinfo_ipv6addr_py *self)
if( self->addrdata ) {
free_ipv6addresses(self->addrdata);
}
- self->ob_type->tp_free((PyObject*)self);
+ Py_TYPE(self)->tp_free((PyObject*)self);
}
@@ -80,7 +80,11 @@ int _ethtool_etherinfo_ipv6_init(etherinfo_ipv6addr_py *self, PyObject *args, Py
PyErr_SetString(PyExc_AttributeError, "Invalid data pointer to constructor");
return -1;
}
+#if PY_MAJOR_VERSION >= 3
+ self->addrdata = (struct ipv6address *) PyCapsule_GetPointer(ethinf_ptr, NULL);
+#else
self->addrdata = (struct ipv6address *) PyCObject_AsVoidPtr(ethinf_ptr);
+#endif
return 0;
}
@@ -105,7 +109,11 @@ PyObject *_ethtool_etherinfo_ipv6_getter(etherinfo_ipv6addr_py *self, PyObject *
if( strcmp(attr, "address") == 0 ) {
ret = RETURN_STRING(self->addrdata->address);
} else if( strcmp(attr, "netmask") == 0 ) {
+#if PY_MAJOR_VERSION >= 3
+ ret = PyLong_FromLong(self->addrdata->netmask);
+#else
ret = PyInt_FromLong(self->addrdata->netmask);
+#endif
} else if( strcmp(attr, "scope") == 0 ) {
char scope[66];
@@ -187,8 +195,7 @@ static PyMemberDef _ethtool_etherinfo_ipv6_members[] = {
*
*/
PyTypeObject ethtool_etherinfoIPv6Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT(NULL, 0)
"ethtool.etherinfo_ipv6addr", /*tp_name*/
sizeof(etherinfo_ipv6addr_py), /*tp_basicsize*/
0, /*tp_itemsize*/
diff --git a/python-ethtool/etherinfo_obj.c b/python-ethtool/etherinfo_obj.c
index dad426b..83eea08 100644
--- a/python-ethtool/etherinfo_obj.c
+++ b/python-ethtool/etherinfo_obj.c
@@ -47,7 +47,7 @@ void _ethtool_etherinfo_dealloc(etherinfo_py *self)
}
free(self->data);
}
- self->ob_type->tp_free((PyObject*)self);
+ Py_TYPE(self)->tp_free((PyObject*)self);
}
@@ -87,7 +87,11 @@ int _ethtool_etherinfo_init(etherinfo_py *self, PyObject *args, PyObject *kwds)
PyErr_SetString(PyExc_AttributeError, "Invalid data pointer to constructor");
return -1;
}
+#if PY_MAJOR_VERSION >= 3
+ self->data = (struct etherinfo_obj_data *) PyCapsule_GetPointer(ethinf_ptr, NULL);
+#else
self->data = (struct etherinfo_obj_data *) PyCObject_AsVoidPtr(ethinf_ptr);
+#endif
return 0;
}
@@ -164,9 +168,17 @@ PyObject *_ethtool_etherinfo_getter(etherinfo_py *self, PyObject *attr_o)
get_etherinfo(self->data, NLQRY_ADDR);
py_addr = get_last_address(self);
if (py_addr) {
+#if PY_MAJOR_VERSION >= 3
+ return PyLong_FromLong(py_addr->ipv4_netmask);
+#else
return PyInt_FromLong(py_addr->ipv4_netmask);
+#endif
}
+#if PY_MAJOR_VERSION >= 3
+ return PyLong_FromLong(0);
+#else
return PyInt_FromLong(0);
+#endif
} else if( strcmp(attr, "ipv4_broadcast") == 0 ) {
get_etherinfo(self->data, NLQRY_ADDR);
py_addr = get_last_address(self);
@@ -312,7 +324,11 @@ PyObject * _ethtool_etherinfo_get_ipv6_addresses(etherinfo_py *self, PyObject *n
struct ipv6address *next = ipv6->next;
ipv6->next = NULL;
+#if PY_MAJOR_VERSION >= 3
+ ipv6_pydata = PyCapsule_New(ipv6, NULL, NULL);
+#else
ipv6_pydata = PyCObject_FromVoidPtr(ipv6, NULL);
+#endif
if( !ipv6_pydata ) {
PyErr_SetString(PyExc_MemoryError,
"[INTERNAL] Failed to create python object "
@@ -363,8 +379,7 @@ static PyMethodDef _ethtool_etherinfo_methods[] = {
*
*/
PyTypeObject ethtool_etherinfoType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT(NULL, 0)
"ethtool.etherinfo", /*tp_name*/
sizeof(etherinfo_py), /*tp_basicsize*/
0, /*tp_itemsize*/
diff --git a/python-ethtool/etherinfo_struct.h b/python-ethtool/etherinfo_struct.h
index bcb692d..8ce54eb 100644
--- a/python-ethtool/etherinfo_struct.h
+++ b/python-ethtool/etherinfo_struct.h
@@ -97,7 +97,11 @@ typedef struct {
*
* @return Returns a PyObject with either the input string wrapped up, or a Python None value.
*/
+#if PY_MAJOR_VERSION >= 3
+#define RETURN_STRING(str) (str ? PyUnicode_FromString(str) : (Py_INCREF(Py_None), Py_None))
+#else
#define RETURN_STRING(str) (str ? PyString_FromString(str) : (Py_INCREF(Py_None), Py_None))
+#endif
PyObject *
make_python_address_from_rtnl_addr(struct nl_object *obj,
diff --git a/python-ethtool/ethtool.c b/python-ethtool/ethtool.c
index a79c438..2e86dba 100644
--- a/python-ethtool/ethtool.c
+++ b/python-ethtool/ethtool.c
@@ -31,6 +31,24 @@
#include "etherinfo_obj.h"
#include "etherinfo.h"
+#if PY_MAJOR_VERSION >= 3
+ #define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
+ #define MOD_DEF(ob, name, doc, methods) \
+ static struct PyModuleDef moduledef = { \
+ PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
+ ob = PyModule_Create(&moduledef);
+ #define MOD_ERROR_VAL NULL
+ #define MOD_SUCCESS_VAL(val) val
+#else
+ #define MOD_INIT(name) PyMODINIT_FUNC init##name(void)
+ #define MOD_DEF(ob, name, doc, methods) \
+ ob = Py_InitModule3(name, methods, doc);
+ #define MOD_ERROR_VAL
+ #define MOD_SUCCESS_VAL(val)
+#endif
+
+
+
static struct nl_handle *nlconnection = NULL;
unsigned int nlconnection_users = 0; /* How many NETLINK users are active? */
extern PyTypeObject ethtool_etherinfoType;
@@ -111,7 +129,6 @@ static PyObject *get_active_devices(PyObject *self __unused, PyObject *args __un
static PyObject *get_devices(PyObject *self __unused, PyObject *args __unused)
{
char buffer[256];
- char *ret;;
PyObject *list = PyList_New(0);
FILE *fd = fopen(_PATH_PROCNET_DEV, "r");
@@ -120,7 +137,8 @@ static PyObject *get_devices(PyObject *self __unused, PyObject *args __unused)
return NULL;
}
/* skip over first two lines */
- ret = fgets(buffer, 256, fd); ret = fgets(buffer, 256, fd);
+ fgets(buffer, 256, fd);
+ fgets(buffer, 256, fd);
while (!feof(fd)) {
PyObject *str;
char *name = buffer;
@@ -321,7 +339,11 @@ static PyObject *get_interfaces_info(PyObject *self __unused, PyObject *args) {
objdata->nlc_users = &nlconnection_users;
/* Instantiate a new etherinfo object with the device information */
+#if PY_MAJOR_VERSION >= 3
+ ethinf_py = PyCapsule_New(objdata, NULL, NULL);
+#else
ethinf_py = PyCObject_FromVoidPtr(objdata, NULL);
+#endif
if( ethinf_py ) {
/* Prepare the argument list for the object constructor */
PyObject *args = PyTuple_New(1);
@@ -749,7 +771,11 @@ static PyObject *__struct_desc_create_dict(struct struct_desc *table,
switch (d->size) {
case sizeof(uint32_t):
+#if PY_MAJOR_VERSION >= 3
+ objval = PyLong_FromLong(*(uint32_t *)val);
+#else
objval = PyInt_FromLong(*(uint32_t *)val);
+#endif
break;
}
@@ -794,7 +820,11 @@ static int __struct_desc_from_dict(struct struct_desc *table,
PyErr_SetString(PyExc_IOError, buf);
return -1;
}
+#if PY_MAJOR_VERSION >= 3
+ *(uint32_t *)val = PyLong_AsLong(obj);
+#else
*(uint32_t *)val = PyInt_AsLong(obj);
+#endif
break;
default:
snprintf(buf, sizeof(buf),
@@ -981,26 +1011,25 @@ static struct PyMethodDef PyEthModuleMethods[] = {
{ .ml_name = NULL, },
};
-
-PyMODINIT_FUNC initethtool(void)
+MOD_INIT(ethtool)
{
PyObject *m;
- m = Py_InitModule3("ethtool", PyEthModuleMethods, "Python ethtool module");
+ MOD_DEF(m, "ethtool", "Python ethtool module", PyEthModuleMethods)
// Prepare the ethtool.etherinfo class
if (PyType_Ready(ðtool_etherinfoType) < 0)
- return;
+ return MOD_ERROR_VAL;
Py_INCREF(ðtool_etherinfoType);
PyModule_AddObject(m, "etherinfo", (PyObject *)ðtool_etherinfoType);
// Prepare the ethtool.etherinfo_ipv6addr class
if (PyType_Ready(ðtool_etherinfoIPv6Type) < 0)
- return;
+ return MOD_ERROR_VAL;
Py_INCREF(ðtool_etherinfoIPv6Type);
PyModule_AddObject(m, "etherinfo_ipv6addr", (PyObject *)ðtool_etherinfoIPv6Type);
if (PyType_Ready(ðtool_netlink_ipv4_address_Type))
- return;
+ return MOD_ERROR_VAL;
// Setup constants
PyModule_AddIntConstant(m, "IFF_UP", IFF_UP); /* Interface is up. */
@@ -1022,5 +1051,6 @@ PyMODINIT_FUNC initethtool(void)
PyModule_AddIntConstant(m, "AF_INET", AF_INET); /* IPv4 interface */
PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IPv6 interface */
PyModule_AddStringConstant(m, "version", "python-ethtool v" VERSION);
+ return MOD_SUCCESS_VAL(m);
}
diff --git a/setup.py b/setup.py
index 99dc718..257a59a 100644
--- a/setup.py
+++ b/setup.py
@@ -1,11 +1,13 @@
-#!/usr/bin/python2
+#!/usr/bin/python
+from __future__ import print_function
from distutils.core import setup, Extension
-import commands
+from subprocess import PIPE, Popen
import sys
version = '0.8'
+
def pkgconfig(pkg):
def _str2list(pkgstr, onlystr):
res = []
@@ -14,27 +16,34 @@ def pkgconfig(pkg):
res.append(l.replace(onlystr, "", 1))
return res
- (res, cflags) = commands.getstatusoutput('pkg-config --cflags-only-other %s' % pkg)
- if res != 0:
- print 'Failed to query pkg-config --cflags-only-other %s' % pkg
+ proc = Popen(['pkg-config', '--cflags-only-other', pkg], stdout=PIPE,
+ stderr=PIPE, universal_newlines=True)
+ cflags, _ = proc.communicate()
+ if proc.returncode:
+ print('Failed to query pkg-config --cflags-only-other %s' % pkg)
sys.exit(1)
- (res, includes) = commands.getstatusoutput('pkg-config --cflags-only-I %s' % pkg)
- if res != 0:
- print 'Failed to query pkg-config --cflags-only-I %s' % pkg
+ proc = Popen(['pkg-config', '--cflags-only-I', pkg], stdout=PIPE,
+ stderr=PIPE, universal_newlines=True)
+ includes, _ = proc.communicate()
+ if proc.returncode:
+ print('Failed to query pkg-config --cflags-only-I %s' % pkg)
sys.exit(1)
- (res, libs) = commands.getstatusoutput('pkg-config --libs-only-l %s' % pkg)
- if res != 0:
- print 'Failed to query pkg-config --libs-only-l %s' % pkg
+ proc = Popen(['pkg-config', '--libs-only-l', pkg], stdout=PIPE,
+ stderr=PIPE, universal_newlines=True)
+ libs, _ = proc.communicate()
+ if proc.returncode:
+ print('Failed to query pkg-config --libs-only-l %s' % pkg)
sys.exit(1)
- (res, libdirs) = commands.getstatusoutput('pkg-config --libs-only-L %s' % pkg)
- if res != 0:
- print 'Failed to query pkg-config --libs-only-L %s' % pkg
+ proc = Popen(['pkg-config', '--libs-only-L', pkg], stdout=PIPE,
+ stderr=PIPE, universal_newlines=True)
+ libdirs, _ = proc.communicate()
+ if proc.returncode:
+ print('Failed to query pkg-config --libs-only-L %s' % pkg)
sys.exit(1)
-
# Clean up the results and return what we've extracted from pkg-config
return {'cflags': cflags,
'include': _str2list(includes, '-I'),
diff --git a/tests/test_ethtool.py b/tests/test_ethtool.py
index 32b6b36..abe023a 100755
--- a/tests/test_ethtool.py
+++ b/tests/test_ethtool.py
@@ -61,7 +61,7 @@ class EthtoolTests(unittest.TestCase):
"""
try:
fn(*args)
- except IOError, e:
+ except IOError as e:
# Check the details of the exception:
self.assertEquals(e.args, (errmsg, ))
else:
--
1.8.4.2
More information about the python-ethtool-devel
mailing list