diff --git a/requirements-dev.txt b/requirements-dev.txt index 37123724..6bbf9447 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,3 +5,5 @@ diff_cover mock pytest pytest-cov +# dependencies also in setup.py until they can be used +six diff --git a/setup.py b/setup.py index 9fb2bd83..e7881222 100644 --- a/setup.py +++ b/setup.py @@ -35,5 +35,6 @@ ], requires=[ 'branding', + 'six', ], ) diff --git a/tests/test_cpio.py b/tests/test_cpio.py index 84763b26..4cb13825 100644 --- a/tests/test_cpio.py +++ b/tests/test_cpio.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os import shutil import subprocess @@ -113,7 +114,7 @@ def test_bz2(self): def test_xz(self): if not self.doXZ: raise unittest.SkipTest("lzma package or xz tool not available") - print 'Running test for XZ' + print('Running test for XZ') self.doArchive('archive.cpio.xz', 'xz') # CpioFileCompat testing diff --git a/tests/test_ifrename_logic.py b/tests/test_ifrename_logic.py index 9fa9255c..c74522eb 100644 --- a/tests/test_ifrename_logic.py +++ b/tests/test_ifrename_logic.py @@ -1,3 +1,4 @@ +from __future__ import print_function import logging import sys import unittest @@ -43,15 +44,15 @@ def tearDown(self): self.siobuff.close() def debug_state(self, ts): - print >>sys.stderr, "" - print >>sys.stderr, self.siobuff.getvalue() - print >>sys.stderr, "" + print("", file=sys.stderr) + print(self.siobuff.getvalue(), file=sys.stderr) + print("", file=sys.stderr) if len(ts): for (s,d) in ts: - print >>sys.stderr, "'%s' -> '%s'" % (s, d) + print("'%s' -> '%s'" % (s, d), file=sys.stderr) else: - print >>sys.stderr, "No transactions" - print >>sys.stderr, "" + print("No transactions", file=sys.stderr) + print("", file=sys.stderr) def test_newhw_norules_1eth(self): @@ -268,16 +269,16 @@ def tearDown(self): self.siobuff.close() def debug_state(self, ts): - print >>sys.stderr, "" - print >>sys.stderr, self.siobuff.getvalue() - print >>sys.stderr, "" + print("", file=sys.stderr) + print(self.siobuff.getvalue(), file=sys.stderr) + print("", file=sys.stderr) if len(ts): - print >>sys.stderr, "Transactions:" + print("Transactions:", file=sys.stderr) for (s,d) in ts: - print >>sys.stderr, "'%s' -> '%s'" % (s, d) + print("'%s' -> '%s'" % (s, d), file=sys.stderr) else: - print >>sys.stderr, "No transactions" - print >>sys.stderr, "" + print("No transactions", file=sys.stderr) + print("", file=sys.stderr) def test_usecase1(self): """ @@ -559,7 +560,7 @@ def assertNotRaises(self, excp, fn, *argl, **kwargs): """Because unittest.TestCase seems to be missing this functionality""" try: fn(*argl, **kwargs) - except excp, e: + except excp as e: self.fail("function raised %s unexpectedly: %s" % (excp, e)) diff --git a/tests/test_pci.py b/tests/test_pci.py index 736b55de..ac03c375 100644 --- a/tests/test_pci.py +++ b/tests/test_pci.py @@ -9,7 +9,6 @@ class TestInvalid(unittest.TestCase): def test_invalid_types(self): self.assertRaises(TypeError, PCI, 0) - self.assertRaises(TypeError, PCI, 0L) self.assertRaises(TypeError, PCI, (0,)) self.assertRaises(TypeError, PCI, []) self.assertRaises(TypeError, PCI, {}) diff --git a/xcp/accessor.py b/xcp/accessor.py index 22f9e24f..7763cf96 100644 --- a/xcp/accessor.py +++ b/xcp/accessor.py @@ -28,7 +28,6 @@ import ftplib import os import tempfile -import types import urllib import urllib2 import urlparse @@ -118,7 +117,7 @@ def openAddress(self, addr): class MountingAccessor(FilesystemAccessor): def __init__(self, mount_types, mount_source, mount_options = None): - ro = isinstance(mount_options, types.ListType) and 'ro' in mount_options + ro = isinstance(mount_options, list) and 'ro' in mount_options super(MountingAccessor, self).__init__(None, ro) self.mount_types = mount_types @@ -135,7 +134,7 @@ def start(self): try: opts = self.mount_options if fs == 'iso9660': - if isinstance(opts, types.ListType): + if isinstance(opts, list): if 'ro' not in opts: opts.append('ro') else: diff --git a/xcp/bootloader.py b/xcp/bootloader.py index 51e362e8..0602b822 100644 --- a/xcp/bootloader.py +++ b/xcp/bootloader.py @@ -23,6 +23,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +from __future__ import print_function import os import os.path import re @@ -431,7 +432,7 @@ def create_label(title): # If this fails, it is probably a string, so leave it unchanged. try: default = menu_order[int(default)] - except ValueError, KeyError: + except (ValueError, KeyError): pass finally: fh.close() @@ -455,47 +456,47 @@ def loadExisting(cls, root = '/'): elif os.path.exists(os.path.join(root, "boot/grub/menu.lst")): return cls.readGrub(os.path.join(root, "boot/grub/menu.lst")) else: - raise RuntimeError, "No existing bootloader configuration found" + raise RuntimeError("No existing bootloader configuration found") def writeExtLinux(self, dst_file = None): if hasattr(dst_file, 'name'): fh = dst_file else: fh = open(dst_file, 'w') - print >> fh, "# location " + self.location + print("# location " + self.location, file=fh) if self.serial: if self.serial.get('flow', None) is None: - print >> fh, "serial %s %s" % (self.serial['port'], - self.serial['baud']) + print("serial %s %s" % (self.serial['port'], + self.serial['baud']), file=fh) else: - print >> fh, "serial %s %s %s" % (self.serial['port'], - self.serial['baud'], - self.serial['flow']) + print("serial %s %s %s" % (self.serial['port'], + self.serial['baud'], + self.serial['flow']), file=fh) if self.default: - print >> fh, "default " + self.default - print >> fh, "prompt 1" + print("default " + self.default, file=fh) + print("prompt 1", file=fh) if self.timeout: - print >> fh, "timeout %d" % self.timeout + print("timeout %d" % self.timeout, file=fh) for label in self.menu_order: - print >> fh, "\nlabel " + label + print("\nlabel " + label, file=fh) m = self.menu[label] if m.title: - print >> fh, " # " + m.title + print(" # " + m.title, file=fh) if m.tboot: - print >> fh, " kernel mboot.c32" - print >> fh, " append %s %s --- %s %s --- %s %s --- %s" % \ - (m.tboot, m.tboot_args, m.hypervisor, m.hypervisor_args, - m.kernel, m.kernel_args, m.initrd) + print(" kernel mboot.c32", file=fh) + print(" append %s %s --- %s %s --- %s %s --- %s" % + (m.tboot, m.tboot_args, m.hypervisor, m.hypervisor_args, + m.kernel, m.kernel_args, m.initrd), file=fh) elif m.hypervisor: - print >> fh, " kernel mboot.c32" - print >> fh, " append %s %s --- %s %s --- %s" % \ - (m.hypervisor, m.hypervisor_args, m.kernel, m.kernel_args, m.initrd) + print(" kernel mboot.c32", file=fh) + print(" append %s %s --- %s %s --- %s" % + (m.hypervisor, m.hypervisor_args, m.kernel, m.kernel_args, m.initrd), file=fh) else: - print >> fh, " kernel " + m.kernel - print >> fh, " append " + m.kernel_args - print >> fh, " initrd " + m.initrd + print(" kernel " + m.kernel, file=fh) + print(" append " + m.kernel_args, file=fh) + print(" initrd " + m.initrd, file=fh) if not hasattr(dst_file, 'name'): fh.close() @@ -504,32 +505,32 @@ def writeGrub(self, dst_file = None): fh = dst_file else: fh = open(dst_file, 'w') - print >> fh, "# location " + self.location + print("# location " + self.location, file=fh) if self.serial: - print >> fh, "serial --unit=%s --speed=%s" % (self.serial['port'], - self.serial['baud']) - print >> fh, "terminal --timeout=10 console serial" + print("serial --unit=%s --speed=%s" % + (self.serial['port'], self.serial['baud']), file=fh) + print("terminal --timeout=10 console serial", file=fh) else: - print >> fh, "terminal console" + print("terminal console", file=fh) if self.default: for i in range(len(self.menu_order)): if self.menu_order[i] == self.default: - print >> fh, "default %d" % i + print("default %d" % i, file=fh) break if self.timeout: - print >> fh, "timeout %d" % (self.timeout / 10) + print("timeout %d" % (self.timeout / 10), file=fh) for label in self.menu_order: m = self.menu[label] - print >> fh, "\ntitle " + m.title + print("\ntitle " + m.title, file=fh) if m.hypervisor: - print >> fh, " kernel " + m.hypervisor + " " + m.hypervisor_args - print >> fh, " module " + m.kernel + " " + m.kernel_args - print >> fh, " module " + m.initrd + print(" kernel " + m.hypervisor + " " + m.hypervisor_args, file=fh) + print(" module " + m.kernel + " " + m.kernel_args, file=fh) + print(" module " + m.initrd, file=fh) else: - print >> fh, " kernel " + m.kernel + " " + m.kernel_args - print >> fh, " initrd " + m.initrd + print(" kernel " + m.kernel + " " + m.kernel_args, file=fh) + print(" initrd " + m.initrd, file=fh) if not hasattr(dst_file, 'name'): fh.close() @@ -540,19 +541,19 @@ def writeGrub2(self, dst_file = None): fh = open(dst_file, 'w') if self.serial: - print >> fh, "serial --unit=%s --speed=%s" % (self.serial['port'], - self.serial['baud']) - print >> fh, "terminal_input serial console" - print >> fh, "terminal_output serial console" + print("serial --unit=%s --speed=%s" % (self.serial['port'], + self.serial['baud']), file=fh) + print("terminal_input serial console", file=fh) + print("terminal_output serial console", file=fh) if self.default: for i in range(len(self.menu_order)): if self.menu_order[i] == self.default: - print >> fh, "set default=%d" % i + print("set default=%d" % i, file=fh) break else: - print >> fh, "set default='%s'" % str(self.default) + print("set default='%s'" % str(self.default), file=fh) if self.timeout: - print >> fh, "set timeout=%d" % (self.timeout / 10) + print("set timeout=%d" % (self.timeout / 10), file=fh) boilerplate = getattr(self, 'boilerplate', [])[:] boilerplate.reverse() @@ -563,41 +564,41 @@ def writeGrub2(self, dst_file = None): if boilerplate: text = boilerplate.pop() if text: - print >> fh, "\n".join(text) + print("\n".join(text), file=fh) extra = ' ' try: extra = m.extra except AttributeError: pass - print >> fh, "menuentry '%s'%s{" % (m.title, extra) + print("menuentry '%s'%s{" % (m.title, extra), file=fh) try: contents = "\n".join(m.contents) if contents: - print >> fh, contents + print(contents, file=fh) except AttributeError: pass if m.root: - print >> fh, "\tsearch --label --set root %s" % m.root + print("\tsearch --label --set root %s" % m.root, file=fh) if m.hypervisor: if m.tboot: - print >> fh, "\tmultiboot2 %s %s" % (m.tboot, m.tboot_args) - print >> fh, "\tmodule2 %s %s" % (m.hypervisor, m.hypervisor_args) + print("\tmultiboot2 %s %s" % (m.tboot, m.tboot_args), file=fh) + print("\tmodule2 %s %s" % (m.hypervisor, m.hypervisor_args), file=fh) else: - print >> fh, "\tmultiboot2 %s %s" % (m.hypervisor, m.hypervisor_args) + print("\tmultiboot2 %s %s" % (m.hypervisor, m.hypervisor_args), file=fh) if m.kernel: - print >> fh, "\tmodule2 %s %s" % (m.kernel, m.kernel_args) + print("\tmodule2 %s %s" % (m.kernel, m.kernel_args), file=fh) if m.initrd: - print >> fh, "\tmodule2 %s" % m.initrd + print("\tmodule2 %s" % m.initrd, file=fh) else: if m.kernel: - print >> fh, "\tlinux %s %s" % (m.kernel, m.kernel_args) + print("\tlinux %s %s" % (m.kernel, m.kernel_args), file=fh) if m.initrd: - print >> fh, "\tinitrd %s" % m.initrd - print >> fh, "}" + print("\tinitrd %s" % m.initrd, file=fh) + print("}", file=fh) if not hasattr(dst_file, 'name'): fh.close() @@ -642,9 +643,9 @@ def newDefault(cls, kernel_link_name, initrd_link_name, root = '/'): if b.menu[b.default].kernel != kernel_link_name: backup = [] if not os.path.exists(os.path.join(root, kernel_link_name[1:])): - raise RuntimeError, "kernel symlink not found" + raise RuntimeError("kernel symlink not found") if not os.path.exists(os.path.join(root, initrd_link_name[1:])): - raise RuntimeError, "initrd symlink not found" + raise RuntimeError("initrd symlink not found") old_kernel_link = b.menu[b.default].kernel old_ver = 'old' m = re.search(r'(-\d+\.\d+)-', old_kernel_link) diff --git a/xcp/cpiofile.py b/xcp/cpiofile.py index a490aeff..79ffcd4e 100755 --- a/xcp/cpiofile.py +++ b/xcp/cpiofile.py @@ -33,6 +33,7 @@ Derived from Lars Gust�bel's tarfile.py """ +from __future__ import print_function __version__ = "0.1" __author__ = "Simon Rowe" @@ -55,7 +56,7 @@ # handling. In many places it is assumed a simple substitution of / by the # local os.path.sep is good enough to convert pathnames, but this does not # work with the mac rooted:path:name versus :nonrooted:path:name syntax - raise ImportError, "cpiofile does not work for platform==mac" + raise ImportError("cpiofile does not work for platform==mac") try: import grp as GRP, pwd as PWD @@ -78,26 +79,26 @@ #--------------------------------------------------------- # Bits used in the mode field, values in octal. #--------------------------------------------------------- -S_IFLNK = 0120000 # symbolic link -S_IFREG = 0100000 # regular file -S_IFBLK = 0060000 # block device -S_IFDIR = 0040000 # directory -S_IFCHR = 0020000 # character device -S_IFIFO = 0010000 # fifo - -TSUID = 04000 # set UID on execution -TSGID = 02000 # set GID on execution -TSVTX = 01000 # reserved - -TUREAD = 0400 # read by owner -TUWRITE = 0200 # write by owner -TUEXEC = 0100 # execute/search by owner -TGREAD = 0040 # read by group -TGWRITE = 0020 # write by group -TGEXEC = 0010 # execute/search by group -TOREAD = 0004 # read by other -TOWRITE = 0002 # write by other -TOEXEC = 0001 # execute/search by other +S_IFLNK = 0o120000 # symbolic link +S_IFREG = 0o100000 # regular file +S_IFBLK = 0o060000 # block device +S_IFDIR = 0o040000 # directory +S_IFCHR = 0o020000 # character device +S_IFIFO = 0o010000 # fifo + +TSUID = 0o4000 # set UID on execution +TSGID = 0o2000 # set GID on execution +TSVTX = 0o1000 # reserved + +TUREAD = 0o400 # read by owner +TUWRITE = 0o200 # write by owner +TUEXEC = 0o100 # execute/search by owner +TGREAD = 0o040 # read by group +TGWRITE = 0o020 # write by group +TGEXEC = 0o010 # execute/search by group +TOREAD = 0o004 # read by other +TOWRITE = 0o002 # write by other +TOEXEC = 0o001 # execute/search by other #--------------------------------------------------------- # Some useful functions @@ -253,7 +254,7 @@ def __init__(self, name, mode, comptype, fileobj, bufsize): self.fileobj = fileobj self.bufsize = bufsize self.buf = "" - self.pos = 0L + self.pos = 0 self.closed = False if comptype == "gz": @@ -347,8 +348,8 @@ def close(self): # while the same crc on a 64-bit box may "look positive". # To avoid irksome warnings from the `struct` module, force # it to look positive on all boxes. - self.fileobj.write(struct.pack(" 1: - if self.hardlinks and self.inodes.has_key(cpioinfo.ino): + if self.hardlinks and cpioinfo.ino in self.inodes: # this inode has already been added cpioinfo.size = 0 self.inodes[cpioinfo.ino].append(cpioinfo.name) @@ -1418,7 +1418,7 @@ def extractall(self, path=".", members=None): # Extract directory with a safe mode, so that # all files below can be extracted as well. try: - os.makedirs(os.path.join(path, cpioinfo.name), 0777) + os.makedirs(os.path.join(path, cpioinfo.name), 0o777) except EnvironmentError: pass directories.append(cpioinfo) @@ -1436,7 +1436,7 @@ def extractall(self, path=".", members=None): self.chown(cpioinfo, path) self.utime(cpioinfo, path) self.chmod(cpioinfo, path) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1462,7 +1462,7 @@ def extract(self, member, path=""): try: self._extract_member(cpioinfo, os.path.join(path, cpioinfo.name)) - except EnvironmentError, e: + except EnvironmentError as e: if self.errorlevel > 0: raise else: @@ -1470,7 +1470,7 @@ def extract(self, member, path=""): self._dbg(1, "cpiofile: %s" % e.strerror) else: self._dbg(1, "cpiofile: %s %r" % (e.strerror, e.filename)) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1525,7 +1525,7 @@ def _extract_member(self, cpioinfo, cpiogetpath): if upperdirs and not os.path.exists(upperdirs): ti = CpioInfo() ti.name = upperdirs - ti.mode = S_IFDIR | 0777 + ti.mode = S_IFDIR | 0o777 ti.mtime = cpioinfo.mtime ti.uid = cpioinfo.uid ti.gid = cpioinfo.gid @@ -1567,7 +1567,7 @@ def makedir(self, cpioinfo, cpiogetpath): """ try: os.mkdir(cpiogetpath) - except EnvironmentError, e: + except EnvironmentError as e: if e.errno != errno.EEXIST: raise @@ -1578,7 +1578,7 @@ def makefile(self, cpioinfo, cpiogetpath): if cpioinfo.nlink == 1: extractinfo = cpioinfo else: - if self.inodes.has_key(cpioinfo.ino): + if cpioinfo.ino in self.inodes: # actual file exists, create link # FIXME handle platforms that don't support hardlinks os.link(os.path.join(cpioinfo._link_path, @@ -1738,7 +1738,7 @@ def next(self): cpioinfo = self.proc_member(cpioinfo) - except ValueError, e: + except ValueError as e: if self.offset == 0: raise ReadError("empty, unreadable or compressed " "file: %s" % e) @@ -1803,7 +1803,7 @@ def _load(self): members. """ while True: - cpioinfo = self.next() + cpioinfo = next(self) if cpioinfo is None: break self._loaded = True @@ -1829,7 +1829,7 @@ def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: - print >> sys.stderr, msg + print(msg, file=sys.stderr) # class CpioFile class CpioIter(object): @@ -1856,7 +1856,7 @@ def next(self): # happen that getmembers() is called during iteration, # which will cause CpioIter to stop prematurely. if not self.cpiofile._loaded: - cpioinfo = self.cpiofile.next() + cpioinfo = next(self.cpiofile) if not cpioinfo: self.cpiofile._loaded = True raise StopIteration diff --git a/xcp/dom0.py b/xcp/dom0.py index f2ca7097..66a23a9e 100644 --- a/xcp/dom0.py +++ b/xcp/dom0.py @@ -23,9 +23,10 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +from __future__ import absolute_import import re -import version +from . import version import sys def default_memory_v2(host_mem_kib): diff --git a/xcp/environ.py b/xcp/environ.py index 27e57323..8223cca8 100644 --- a/xcp/environ.py +++ b/xcp/environ.py @@ -47,8 +47,8 @@ def readInventory(root = '/'): try: fh = open(os.path.join(root, 'etc/xensource-inventory')) - for line in ( x for x in ( y.strip() for y in fh.xreadlines() ) - if not x.startswith('#') ): + for line in (x for x in (y.strip() for y in fh) + if not x.startswith('#')): vals = line.split('=', 1) @@ -59,7 +59,7 @@ def readInventory(root = '/'): d[vals[0]] = vals[1].strip('"\'') - except IOError, e: + except IOError as e: raise InventoryError("Error reading from file '%s'" % (e,)) finally: diff --git a/xcp/mount.py b/xcp/mount.py index 60d191bc..49b0a2e8 100644 --- a/xcp/mount.py +++ b/xcp/mount.py @@ -52,13 +52,13 @@ def mount(dev, mountpoint, options = None, fstype = None, label = None): rc, out, err = xcp.cmd.runCmd(cmd, with_stdout=True, with_stderr=True) if rc != 0: - raise MountException, "out: '%s' err: '%s'" % (out, err) + raise MountException("out: '%s' err: '%s'" % (out, err)) def bindMount(source, mountpoint): cmd = [ '/bin/mount', '--bind', source, mountpoint] rc, out, err = xcp.cmd.runCmd(cmd, with_stdout=True, with_stderr=True) if rc != 0: - raise MountException, "out: '%s' err: '%s'" % (out, err) + raise MountException("out: '%s' err: '%s'" % (out, err)) def umount(mountpoint, force = False): # -d option also removes the loop device (if present) diff --git a/xcp/net/ifrename/dynamic.py b/xcp/net/ifrename/dynamic.py index 62844848..befab65a 100644 --- a/xcp/net/ifrename/dynamic.py +++ b/xcp/net/ifrename/dynamic.py @@ -104,7 +104,7 @@ def load_and_parse(self): LOG.error("No source of data to parse") return False - except IOError, e: + except IOError as e: LOG.error("IOError while reading file: %s" % (e,)) return False finally: @@ -137,7 +137,7 @@ def load_and_parse(self): if len(entry) != 3: raise ValueError("Expected 3 entries") macpci = MACPCI(entry[0], entry[1], tname=entry[2]) - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: LOG.warning("Invalid lastboot data entry: %s" % (e,)) continue @@ -149,7 +149,7 @@ def load_and_parse(self): if len(entry) != 3: raise ValueError("Expected 3 entries") macpci = MACPCI(entry[0], entry[1], tname=entry[2]) - except (TypeError, ValueError), e: + except (TypeError, ValueError) as e: LOG.warning("Invalid old data entry: %s" % (e,)) continue self.old.append(macpci) @@ -178,7 +178,7 @@ def generate(self, state): if nic.mac == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -199,7 +199,7 @@ def generate(self, state): if nic.ppn == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -213,7 +213,7 @@ def generate(self, state): try: nic = pci_sbdfi_to_nic(value, state) rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -226,7 +226,7 @@ def generate(self, state): if nic.label == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -257,7 +257,7 @@ def validate(entry): return False MACPCI(entry[0], entry[1], tname=entry[2]) return True - except Exception, e: + except Exception as e: LOG.warning("Failed to validate '%s' because '%s'" % (entry, e)) return False @@ -301,7 +301,7 @@ def save(self, header = True): LOG.error("No source of data to parse") return False - except IOError, e: + except IOError as e: LOG.error("IOError while reading file: %s" % (e,)) return False finally: diff --git a/xcp/net/ifrename/static.py b/xcp/net/ifrename/static.py index 89a77fda..615c2073 100644 --- a/xcp/net/ifrename/static.py +++ b/xcp/net/ifrename/static.py @@ -127,7 +127,7 @@ def load_and_parse(self): LOG.error("No source of data to parse") return False - except IOError, e: + except IOError as e: LOG.error("IOError while reading file: %s" % (e,)) return False finally: @@ -230,7 +230,7 @@ def generate(self, state): if nic.mac == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -251,7 +251,7 @@ def generate(self, state): if nic.ppn == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -265,7 +265,7 @@ def generate(self, state): try: nic = pci_sbdfi_to_nic(value, state) rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -278,7 +278,7 @@ def generate(self, state): if nic.label == value: try: rule = MACPCI(nic.mac, nic.pci, tname=target) - except Exception, e: + except Exception as e: LOG.warning("Error creating rule: %s" % (e,)) continue self.rules.append(rule) @@ -340,7 +340,7 @@ def save(self, header = True): LOG.error("No source of data to parse") return False - except IOError, e: + except IOError as e: LOG.error("IOError while reading file: %s" % (e,)) return False finally: diff --git a/xcp/net/mac.py b/xcp/net/mac.py index a675a179..9b042c8f 100644 --- a/xcp/net/mac.py +++ b/xcp/net/mac.py @@ -57,7 +57,7 @@ def __init__(self, addr): """Constructor""" self.octets = [] - self.integer = -1L + self.integer = -1 if isinstance(addr, (str, unicode)): diff --git a/xcp/pci.py b/xcp/pci.py index 8b371152..367e7dc5 100644 --- a/xcp/pci.py +++ b/xcp/pci.py @@ -124,7 +124,7 @@ def __eq__(self, rhs): else: try: return self.integer == PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented def __ne__(self, rhs): @@ -133,7 +133,7 @@ def __ne__(self, rhs): else: try: return self.integer != PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented def __hash__(self): @@ -145,7 +145,7 @@ def __lt__(self, rhs): else: try: return self.integer < PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented def __le__(self, rhs): @@ -154,7 +154,7 @@ def __le__(self, rhs): else: try: return self.integer <= PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented def __gt__(self, rhs): @@ -163,7 +163,7 @@ def __gt__(self, rhs): else: try: return self.integer > PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented def __ge__(self, rhs): @@ -172,7 +172,7 @@ def __ge__(self, rhs): else: try: return self.integer >= PCI(rhs).integer - except StandardError: + except Exception: return NotImplemented @@ -232,7 +232,7 @@ def read(cls): for f in ['/usr/share/hwdata/pci.ids']: if os.path.exists(f): return cls(f) - raise Exception, 'Failed to open PCI database' + raise Exception('Failed to open PCI database') def findVendor(self, vendor): return vendor in self.vendor_dict and self.vendor_dict[vendor] or None diff --git a/xcp/repository.py b/xcp/repository.py index 3da2f17b..98b39683 100644 --- a/xcp/repository.py +++ b/xcp/repository.py @@ -28,6 +28,8 @@ import xml.dom.minidom import ConfigParser +import six + import xcp.version as version import xcp.xmlunwrap as xmlunwrap @@ -187,8 +189,9 @@ def _getVersion(cls, access, category): ver_str = treeinfo.get(category, 'version') repo_ver = version.Version.from_string(ver_str) - except Exception, e: - raise RepoFormatError, "Failed to open %s: %s" % (cls.TREEINFO_FILENAME, str(e)) + except Exception as e: + six.raise_from(RepoFormatError("Failed to open %s: %s" % + (cls.TREEINFO_FILENAME, str(e))), e) access.finish() return repo_ver @@ -230,8 +233,9 @@ def findRepositories(cls, access): for line in extra: package_list.append(line.strip()) extra.close() - except Exception, e: - raise RepoFormatError, "Failed to open %s: %s" % (cls.REPOLIST_FILENAME, str(e)) + except Exception as e: + six.raise_from(RepoFormatError("Failed to open %s: %s" % + (cls.REPOLIST_FILENAME, str(e))), e) for loc in package_list: if cls.isRepo(access, loc): @@ -250,17 +254,17 @@ def __init__(self, access, base, is_group = False): try: repofile = access.openAddress(os.path.join(base, self.REPOSITORY_FILENAME)) - except Exception, e: + except Exception as e: access.finish() - raise NoRepository, e + six.raise_from(NoRepository(), e) self._parse_repofile(repofile) repofile.close() try: pkgfile = access.openAddress(os.path.join(base, self.PKGDATA_FILENAME)) - except Exception, e: + except Exception as e: access.finish() - raise NoRepository, e + six.raise_from(NoRepository(), e) self._parse_packages(pkgfile) pkgfile.close() @@ -289,8 +293,8 @@ def _parse_repofile(self, repofile): # build xml doc object try: xmldoc = xml.dom.minidom.parseString(repofile_contents) - except: - raise RepoFormatError, "%s not in XML" % self.REPOSITORY_FILENAME + except Exception as e: + six.raise_from(RepoFormatError("%s not in XML" % self.REPOSITORY_FILENAME), e) try: repo_node = xmlunwrap.getElementsByTagName(xmldoc, ['repository'], mandatory = True) @@ -313,8 +317,8 @@ def _parse_repofile(self, repofile): del req['build'] assert req['test'] in self.OPER_MAP self.requires.append(req) - except: - raise RepoFormatError, "%s format error" % self.REPOSITORY_FILENAME + except Exception as e: + six.raise_from(RepoFormatError("%s format error" % self.REPOSITORY_FILENAME), e) self.identifier = "%s:%s" % (self.originator, self.name) ver_str = self.version @@ -332,8 +336,8 @@ def _parse_packages(self, pkgfile): # build xml doc object try: xmldoc = xml.dom.minidom.parseString(pkgfile_contents) - except: - raise RepoFormatError, "%s not in XML" % self.PKGDATA_FILENAME + except Exception as e: + six.raise_from(RepoFormatError("%s not in XML" % self.PKGDATA_FILENAME), e) for pkg_node in xmlunwrap.getElementsByTagName(xmldoc, ['package']): pkg = self._create_package(pkg_node) diff --git a/xcp/xmlunwrap.py b/xcp/xmlunwrap.py index 654b84bf..1487afab 100644 --- a/xcp/xmlunwrap.py +++ b/xcp/xmlunwrap.py @@ -23,6 +23,8 @@ """xmlunwrap - general methods to unwrap XML elements & attributes""" +import six + class XmlUnwrapError(Exception): pass @@ -39,7 +41,7 @@ def getElementsByTagName(el, tags, mandatory = False): for tag in tags: matching.extend(el.getElementsByTagName(tag)) if mandatory and len(matching) == 0: - raise XmlUnwrapError, "Missing mandatory element %s" % tags[0] + raise XmlUnwrapError("Missing mandatory element %s" % tags[0]) return matching def getStrAttribute(el, attrs, default = '', mandatory = False): @@ -50,7 +52,7 @@ def getStrAttribute(el, attrs, default = '', mandatory = False): matching.append(val) if len(matching) == 0: if mandatory: - raise XmlUnwrapError, "Missing mandatory attribute %s" % attrs[0] + raise XmlUnwrapError("Missing mandatory attribute %s" % attrs[0]) return default return matching[0] @@ -68,8 +70,8 @@ def getIntAttribute(el, attrs, default = None): return default try: int_val = int(val, 0) - except: - raise XmlUnwrapError, "Invalid integer value for %s" % attrs[0] + except Exception as e: + six.raise_from(XmlUnwrapError("Invalid integer value for %s" % attrs[0]), e) return int_val def getMapAttribute(el, attrs, mapping, default = None): @@ -78,7 +80,7 @@ def getMapAttribute(el, attrs, mapping, default = None): key = getStrAttribute(el, attrs, default, mandatory) if key not in k: - raise XmlUnwrapError, "Unexpected key %s for attribute" % key + raise XmlUnwrapError("Unexpected key %s for attribute" % key) k_list = list(k) return v[k_list.index(key)]