pycodestyle: Do not use bare 'except:'

A bare 'except:' catches all exceptions [1], including SystemExit,
KeyboardInterrupt, and GeneratorExit (which is not an error and should
not normally be caught by user code). In situations where you need to
catch all “normal” errors, you can catch the base class for all normal
exceptions, Exception [2].

[1] https://docs.python.org/2/howto/doanddont.html#except
[2] https://docs.python.org/2/library/exceptions.html#Exception
This commit is contained in:
Radostin Stoyanov 2017-07-24 09:26:48 +01:00 committed by Cole Robinson
parent 2fd6d9aa32
commit b93cc3bbc9
60 changed files with 125 additions and 127 deletions

View File

@ -422,7 +422,7 @@ class TestBaseCommand(distutils.core.Command):
try: try:
import coverage import coverage
use_cov = True use_cov = True
except: except ImportError:
use_cov = False use_cov = False
cov = None cov = None
@ -439,10 +439,8 @@ class TestBaseCommand(distutils.core.Command):
testsmodule.utils.REGENERATE_OUTPUT = bool(self.regenerate_output) testsmodule.utils.REGENERATE_OUTPUT = bool(self.regenerate_output)
if hasattr(unittest, "installHandler"): if hasattr(unittest, "installHandler"):
try: # Install the control-c handler.
unittest.installHandler() unittest.installHandler()
except:
print("installHandler hack failed")
tests = unittest.TestLoader().loadTestsFromNames(self._testfiles) tests = unittest.TestLoader().loadTestsFromNames(self._testfiles)
if self.only: if self.only:

View File

@ -192,7 +192,7 @@ class TestInterfaces(unittest.TestCase):
assert(False) assert(False)
except ValueError: except ValueError:
pass pass
except: except Exception:
assert(False) assert(False)
# protocol_xml test # protocol_xml test

View File

@ -30,4 +30,4 @@ format = pylint
# E741: Do not use variables named l, O, or I # E741: Do not use variables named l, O, or I
ignore = E122, E123, E124, E125, E126, E127, E128, E129, E131, E203, E221, E241, E301, E303, E305, E306, E402, E501, E722, E741 ignore = E122, E123, E124, E125, E126, E127, E128, E129, E131, E203, E221, E241, E301, E303, E305, E306, E402, E501, E741

View File

@ -74,7 +74,7 @@ def exit_cleanup():
for f in cleanup or []: for f in cleanup or []:
try: try:
os.unlink(f) os.unlink(f)
except: except Exception:
pass pass
atexit.register(exit_cleanup) atexit.register(exit_cleanup)

View File

@ -229,7 +229,7 @@ def _testURL(fetcher, distname, arch, distroobj):
xenstore = None xenstore = None
if distroobj.hasxen: if distroobj.hasxen:
xenstore = _storeForDistro(fetcher, xenguest) xenstore = _storeForDistro(fetcher, xenguest)
except: except Exception:
raise AssertionError("\nFailed to detect URLDistro class:\n" raise AssertionError("\nFailed to detect URLDistro class:\n"
"name = %s\n" "name = %s\n"
"url = %s\n\n%s" % "url = %s\n\n%s" %

View File

@ -147,14 +147,14 @@ def test_create(testconn, xml, define_func="defineXML"):
obj.create() obj.create()
obj.destroy() obj.destroy()
obj.undefine() obj.undefine()
except: except Exception:
try: try:
obj.destroy() obj.destroy()
except: except Exception:
pass pass
try: try:
obj.undefine() obj.undefine()
except: except Exception:
pass pass

View File

@ -123,7 +123,7 @@ def main(conn=None):
print_stdout(_("Creating guest '%s'.") % guest.name) print_stdout(_("Creating guest '%s'.") % guest.name)
guest.start_install() guest.start_install()
cli.connect_console(guest, conscb, True) cli.connect_console(guest, conscb, True)
except: except Exception:
converter.cleanup() converter.cleanup()
raise raise

View File

@ -73,7 +73,7 @@ def supports_pxe(guest):
xmlobj = virtinst.Network(nic.conn, parsexml=netobj.XMLDesc(0)) xmlobj = virtinst.Network(nic.conn, parsexml=netobj.XMLDesc(0))
if xmlobj.can_pxe(): if xmlobj.can_pxe():
return True return True
except: except Exception:
logging.debug("Error checking if PXE supported", exc_info=True) logging.debug("Error checking if PXE supported", exc_info=True)
return True return True

View File

@ -1285,7 +1285,7 @@ class vmmAddHardware(vmmGObjectUI):
try: try:
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except: except Exception:
logging.debug("Error looking up pool=%s for refresh after " logging.debug("Error looking up pool=%s for refresh after "
"storage creation.", poolname, exc_info=True) "storage creation.", poolname, exc_info=True)

View File

@ -90,7 +90,7 @@ class vmmAddStorage(vmmGObjectUI):
widget = self.widget("phys-hd-label") widget = self.widget("phys-hd-label")
try: try:
max_storage = self._host_disk_space() max_storage = self._host_disk_space()
except: except Exception:
logging.exception("Error determining host disk space") logging.exception("Error determining host disk space")
widget.set_markup("") widget.set_markup("")
return return

View File

@ -74,7 +74,7 @@ class vmmGObject(GObject.GObject):
self.remove_gobject_timeout(h) self.remove_gobject_timeout(h)
self._cleanup() self._cleanup()
except: except Exception:
logging.exception("Error cleaning up %s", self) logging.exception("Error cleaning up %s", self)
def _cleanup(self): def _cleanup(self):
@ -84,7 +84,7 @@ class vmmGObject(GObject.GObject):
try: try:
if self.config and self._leak_check: if self.config and self._leak_check:
self.config.remove_object(self.object_key) self.config.remove_object(self.object_key)
except: except Exception:
logging.exception("Error removing %s", self.object_key) logging.exception("Error removing %s", self.object_key)
# pylint: disable=arguments-differ # pylint: disable=arguments-differ

View File

@ -858,7 +858,7 @@ class vmmCloneVM(vmmGObjectUI):
try: try:
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except: except Exception:
logging.debug("Error looking up pool=%s for refresh after " logging.debug("Error looking up pool=%s for refresh after "
"VM clone.", poolname, exc_info=True) "VM clone.", poolname, exc_info=True)

View File

@ -199,7 +199,7 @@ class vmmConfig(object):
from guestfs import GuestFS # pylint: disable=import-error from guestfs import GuestFS # pylint: disable=import-error
g = GuestFS(close_on_exit=False) g = GuestFS(close_on_exit=False)
return bool(getattr(g, "add_libvirt_dom", None)) return bool(getattr(g, "add_libvirt_dom", None))
except: except Exception:
return False return False
# General app wide helpers (gsettings agnostic) # General app wide helpers (gsettings agnostic)

View File

@ -47,7 +47,7 @@ def current_user():
try: try:
import getpass import getpass
return getpass.getuser() return getpass.getuser()
except: except Exception:
return "" return ""
@ -472,7 +472,7 @@ class vmmConnect(vmmGObjectUI):
elif self.can_resolve_local is None: elif self.can_resolve_local is None:
try: try:
socket.getaddrinfo(host, None) socket.getaddrinfo(host, None)
except: except Exception:
logging.debug("Couldn't resolve host '%s'. Stripping " logging.debug("Couldn't resolve host '%s'. Stripping "
"'.local' and retrying.", host) "'.local' and retrying.", host)
self.can_resolve_local = False self.can_resolve_local = False
@ -486,7 +486,7 @@ class vmmConnect(vmmGObjectUI):
elif self.can_resolve_hostname is None: elif self.can_resolve_hostname is None:
try: try:
socket.getaddrinfo(host, None) socket.getaddrinfo(host, None)
except: except Exception:
logging.debug("Couldn't resolve host '%s'. Disabling " logging.debug("Couldn't resolve host '%s'. Disabling "
"host name resolution, only using IP addr", "host name resolution, only using IP addr",
host) host)

View File

@ -32,7 +32,7 @@ def do_we_have_session():
pid = os.getpid() pid = os.getpid()
try: try:
bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
except: except Exception:
logging.exception("Error getting system bus handle") logging.exception("Error getting system bus handle")
return return
@ -46,7 +46,7 @@ def do_we_have_session():
ret = manager.GetSessionByPID("(u)", pid) ret = manager.GetSessionByPID("(u)", pid)
logging.debug("Found login1 session=%s", ret) logging.debug("Found login1 session=%s", ret)
return True return True
except: except Exception:
logging.exception("Couldn't connect to logind") logging.exception("Couldn't connect to logind")
return False return False
@ -62,7 +62,7 @@ def creds_dialog(conn, creds):
def wrapper(fn, conn, creds): def wrapper(fn, conn, creds):
try: try:
ret = fn(conn, creds) ret = fn(conn, creds)
except: except Exception:
logging.exception("Error from creds dialog") logging.exception("Error from creds dialog")
ret = -1 ret = -1
retipc.append(ret) retipc.append(ret)

View File

@ -65,7 +65,7 @@ class _ObjectList(vmmGObject):
for obj in self._objects: for obj in self._objects:
try: try:
obj.cleanup() obj.cleanup()
except: except Exception:
logging.debug("Failed to cleanup %s", exc_info=True) logging.debug("Failed to cleanup %s", exc_info=True)
self._objects = [] self._objects = []
finally: finally:
@ -968,7 +968,7 @@ class vmmConnection(vmmGObject):
self._backend.storagePoolEventDeregisterAny(eid) self._backend.storagePoolEventDeregisterAny(eid)
for eid in self._node_device_cb_ids: for eid in self._node_device_cb_ids:
self._backend.nodeDeviceEventDeregisterAny(eid) self._backend.nodeDeviceEventDeregisterAny(eid)
except: except Exception:
logging.debug("Failed to deregister events in conn cleanup", logging.debug("Failed to deregister events in conn cleanup",
exc_info=True) exc_info=True)
finally: finally:
@ -1012,7 +1012,7 @@ class vmmConnection(vmmGObject):
def _do_creds_password(self, creds): def _do_creds_password(self, creds):
try: try:
return connectauth.creds_dialog(self, creds) return connectauth.creds_dialog(self, creds)
except: except Exception:
logging.debug("Launching creds dialog failed", exc_info=True) logging.debug("Launching creds dialog failed", exc_info=True)
return -1 return -1
@ -1136,7 +1136,7 @@ class vmmConnection(vmmGObject):
class_name = obj.class_name() class_name = obj.class_name()
try: try:
name = obj.get_name() name = obj.get_name()
except: except Exception:
name = str(obj) name = str(obj)
if not self._objects.remove(obj): if not self._objects.remove(obj):

View File

@ -1611,7 +1611,7 @@ class vmmCreate(vmmGObjectUI):
try: try:
path, ignore = self._get_storage_path(newname, do_log=False) path, ignore = self._get_storage_path(newname, do_log=False)
self._populate_summary_storage(path=path) self._populate_summary_storage(path=path)
except: except Exception:
logging.debug("Error generating storage path on name change " logging.debug("Error generating storage path on name change "
"for name=%s", newname, exc_info=True) "for name=%s", newname, exc_info=True)
@ -1862,7 +1862,7 @@ class vmmCreate(vmmGObjectUI):
if guest.os.is_arm64(): if guest.os.is_arm64():
try: try:
guest.set_uefi_default() guest.set_uefi_default()
except: except Exception:
# If this errors we will have already informed the user # If this errors we will have already informed the user
# on page 1. # on page 1.
pass pass
@ -2365,7 +2365,7 @@ class vmmCreate(vmmGObjectUI):
distro = installer.detect_distro(self._guest) distro = installer.detect_distro(self._guest)
thread_results.set_distro(distro) thread_results.set_distro(distro)
except: except Exception:
logging.exception("Error detecting distro.") logging.exception("Error detecting distro.")
thread_results.set_failed() thread_results.set_failed()
@ -2394,7 +2394,7 @@ class vmmCreate(vmmGObjectUI):
return return
distro = thread_results.get_distro() distro = thread_results.get_distro()
except: except Exception:
distro = None distro = None
logging.exception("Error in distro detect timeout") logging.exception("Error in distro detect timeout")
@ -2582,7 +2582,7 @@ class vmmCreate(vmmGObjectUI):
try: try:
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except: except Exception:
logging.debug("Error looking up pool=%s for refresh after " logging.debug("Error looking up pool=%s for refresh after "
"VM creation.", poolname, exc_info=True) "VM creation.", poolname, exc_info=True)

View File

@ -50,7 +50,7 @@ def _make_ipaddr(addrstr):
return None return None
try: try:
return ipaddr.IPNetwork(addrstr) return ipaddr.IPNetwork(addrstr)
except: except Exception:
return None return None

View File

@ -66,7 +66,7 @@ class vmmCreateVolume(vmmGObjectUI):
def show(self, parent): def show(self, parent):
try: try:
parent_xml = self.parent_pool.xmlobj.get_xml_config() parent_xml = self.parent_pool.xmlobj.get_xml_config()
except: except Exception:
logging.debug("Error getting parent_pool xml", exc_info=True) logging.debug("Error getting parent_pool xml", exc_info=True)
parent_xml = None parent_xml = None
@ -112,7 +112,7 @@ class vmmCreateVolume(vmmGObjectUI):
try: try:
ret = StorageVolume.find_free_name( ret = StorageVolume.find_free_name(
self.parent_pool.get_backend(), self.name_hint, suffix=suffix) self.parent_pool.get_backend(), self.name_hint, suffix=suffix)
except: except Exception:
logging.exception("Error finding a default vol name") logging.exception("Error finding a default vol name")
return ret return ret

View File

@ -217,7 +217,7 @@ class vmmDeleteDialog(vmmGObjectUI):
try: try:
vol = conn.storageVolLookupByPath(path) vol = conn.storageVolLookupByPath(path)
except: except Exception:
logging.debug("Path '%s' is not managed. Deleting locally", path) logging.debug("Path '%s' is not managed. Deleting locally", path)
if vol: if vol:

View File

@ -696,7 +696,7 @@ class vmmDetails(vmmGObjectUI):
if self.console.details_viewer_is_visible(): if self.console.details_viewer_is_visible():
try: try:
self.console.details_close_viewer() self.console.details_close_viewer()
except: except Exception:
logging.error("Failure when disconnecting from desktop server") logging.error("Failure when disconnecting from desktop server")
self.emit("details-closed") self.emit("details-closed")
@ -827,7 +827,7 @@ class vmmDetails(vmmGObjectUI):
machine=self.vm.get_machtype()) machine=self.vm.get_machtype())
machines = capsinfo.machines[:] machines = capsinfo.machines[:]
except: except Exception:
logging.exception("Error determining machine list") logging.exception("Error determining machine list")
show_machine = (arch not in ["i686", "x86_64"]) show_machine = (arch not in ["i686", "x86_64"])
@ -2979,7 +2979,7 @@ class vmmDetails(vmmGObjectUI):
heads = vid.heads heads = vid.heads
try: try:
ramlabel = ram and "%d MiB" % (int(ram) / 1024) or "-" ramlabel = ram and "%d MiB" % (int(ram) / 1024) or "-"
except: except Exception:
ramlabel = "-" ramlabel = "-"
self.widget("video-ram").set_text(ramlabel) self.widget("video-ram").set_text(ramlabel)

View File

@ -134,7 +134,7 @@ def start_job_progress_thread(vm, meter, progtext):
progress = data_total - data_remaining progress = data_total - data_remaining
meter.update(progress) meter.update(progress)
except: except Exception:
logging.exception("Error calling jobinfo") logging.exception("Error calling jobinfo")
return False return False

View File

@ -230,7 +230,7 @@ class vmmEngine(vmmGObject):
packages = self.config.hv_packages + libvirt_packages packages = self.config.hv_packages + libvirt_packages
ret = packageutils.check_packagekit(manager, manager.err, packages) ret = packageutils.check_packagekit(manager, manager.err, packages)
except: except Exception:
logging.exception("Error talking to PackageKit") logging.exception("Error talking to PackageKit")
if ret: if ret:
@ -573,7 +573,7 @@ class vmmEngine(vmmGObject):
else: else:
try: try:
conn.open() conn.open()
except: except Exception:
return None return None
return conn return conn
except Exception: except Exception:
@ -593,7 +593,7 @@ class vmmEngine(vmmGObject):
win.cleanup() win.cleanup()
self.conns[uri]["conn"].cleanup() self.conns[uri]["conn"].cleanup()
except: except Exception:
logging.exception("Error cleaning up conn in engine") logging.exception("Error cleaning up conn in engine")
@ -1021,7 +1021,7 @@ class vmmEngine(vmmGObject):
return True return True
return False return False
except: except Exception:
# In case of cli error, we may need to exit the app # In case of cli error, we may need to exit the app
logging.debug("Error in cli connection callback", exc_info=True) logging.debug("Error in cli connection callback", exc_info=True)
self._exit_app_if_no_windows() self._exit_app_if_no_windows()
@ -1065,7 +1065,7 @@ class vmmEngine(vmmGObject):
def _handle_cli_command(self, actionobj, variant): def _handle_cli_command(self, actionobj, variant):
try: try:
return self._do_handle_cli_command(actionobj, variant) return self._do_handle_cli_command(actionobj, variant)
except: except Exception:
# In case of cli error, we may need to exit the app # In case of cli error, we may need to exit the app
logging.debug("Error handling cli command", exc_info=True) logging.debug("Error handling cli command", exc_info=True)
self._exit_app_if_no_windows() self._exit_app_if_no_windows()

View File

@ -686,7 +686,7 @@ class vmmHost(vmmGObjectUI):
for net in self.conn.list_nets(): for net in self.conn.list_nets():
try: try:
net.disconnect_by_func(self.refresh_network) net.disconnect_by_func(self.refresh_network)
except: except Exception:
pass pass
net.connect("state-changed", self.refresh_network) net.connect("state-changed", self.refresh_network)
model.append([net.get_connkey(), net.get_name(), "network-idle", model.append([net.get_connkey(), net.get_name(), "network-idle",
@ -936,7 +936,7 @@ class vmmHost(vmmGObjectUI):
for iface in self.conn.list_interfaces(): for iface in self.conn.list_interfaces():
try: try:
iface.disconnect_by_func(self.refresh_interface) iface.disconnect_by_func(self.refresh_interface)
except: except Exception:
pass pass
iface.connect("state-changed", self.refresh_interface) iface.connect("state-changed", self.refresh_interface)
model.append([iface.get_connkey(), iface.get_name(), model.append([iface.get_connkey(), iface.get_name(),

View File

@ -162,10 +162,10 @@ class vmmInspection(vmmGObject):
self._set_vm_inspection_data(vm, data) self._set_vm_inspection_data(vm, data)
else: else:
set_inspection_error(vm) set_inspection_error(vm)
except: except Exception:
set_inspection_error(vm) set_inspection_error(vm)
raise raise
except: except Exception:
logging.exception("%s: exception while processing", prettyvm) logging.exception("%s: exception while processing", prettyvm)
def _inspect_vm(self, conn, vm): def _inspect_vm(self, conn, vm):
@ -217,13 +217,13 @@ class vmmInspection(vmmGObject):
for mp_dev in mps: for mp_dev in mps:
try: try:
g.mount_ro(mp_dev[1], mp_dev[0]) g.mount_ro(mp_dev[1], mp_dev[0])
except: except Exception:
logging.exception("%s: exception mounting %s on %s " logging.exception("%s: exception mounting %s on %s "
"(ignored)", "(ignored)",
prettyvm, mp_dev[1], mp_dev[0]) prettyvm, mp_dev[1], mp_dev[0])
filesystems_mounted = True filesystems_mounted = True
except: except Exception:
logging.exception("%s: exception while mounting disks (ignored)", logging.exception("%s: exception while mounting disks (ignored)",
prettyvm) prettyvm)

View File

@ -57,7 +57,7 @@ class vmmKeyring(object):
"org.freedesktop.Secret.Collection", None) "org.freedesktop.Secret.Collection", None)
logging.debug("Using keyring session %s", self._session) logging.debug("Using keyring session %s", self._session)
except: except Exception:
logging.exception("Error determining keyring") logging.exception("Error determining keyring")
@ -83,7 +83,7 @@ class vmmKeyring(object):
_id = self._collection.CreateItem("(a{sv}(oayays)b)", _id = self._collection.CreateItem("(a{sv}(oayays)b)",
props, params, replace)[0] props, params, replace)[0]
ret = int(_id.rsplit("/")[-1]) ret = int(_id.rsplit("/")[-1])
except: except Exception:
logging.exception("Failed to add keyring secret") logging.exception("Failed to add keyring secret")
return ret return ret
@ -95,7 +95,7 @@ class vmmKeyring(object):
"org.freedesktop.secrets", path, "org.freedesktop.secrets", path,
"org.freedesktop.Secret.Item", None) "org.freedesktop.Secret.Item", None)
iface.Delete("(s)", "/") iface.Delete("(s)", "/")
except: except Exception:
logging.exception("Failed to delete keyring secret") logging.exception("Failed to delete keyring secret")
def get_secret(self, _id): def get_secret(self, _id):
@ -119,7 +119,7 @@ class vmmKeyring(object):
attrs["%s" % key] = "%s" % val attrs["%s" % key] = "%s" % val
ret = vmmSecret(label, secret, attrs) ret = vmmSecret(label, secret, attrs)
except: except Exception:
logging.exception("Failed to get keyring secret id=%s", _id) logging.exception("Failed to get keyring secret id=%s", _id)
return ret return ret

View File

@ -96,7 +96,7 @@ class vmmLibvirtObject(vmmGObject):
def __repr__(self): def __repr__(self):
try: try:
name = self.get_name() name = self.get_name()
except: except Exception:
name = "" name = ""
return "<%s name=%s id=%s>" % ( return "<%s name=%s id=%s>" % (
self.__class__.__name__, name, hex(id(self))) self.__class__.__name__, name, hex(id(self)))
@ -135,7 +135,7 @@ class vmmLibvirtObject(vmmGObject):
try: try:
self._key = newname self._key = newname
self.conn.rename_object(self, origxml, newxml, oldconnkey) self.conn.rename_object(self, origxml, newxml, oldconnkey)
except: except Exception:
self._key = oldname self._key = oldname
raise raise
finally: finally:
@ -196,7 +196,7 @@ class vmmLibvirtObject(vmmGObject):
initialize_failed = False initialize_failed = False
try: try:
self._init_libvirt_state() self._init_libvirt_state()
except: except Exception:
logging.debug("Error initializing libvirt state for %s", self, logging.debug("Error initializing libvirt state for %s", self,
exc_info=True) exc_info=True)
initialize_failed = True initialize_failed = True

View File

@ -78,7 +78,7 @@ def _get_inspection_icon_pixbuf(vm, w, h):
pb.write(png_data) pb.write(png_data)
pb.close() pb.close()
return pb.get_pixbuf() return pb.get_pixbuf()
except: except Exception:
logging.exception("Error loading inspection icon data") logging.exception("Error loading inspection icon data")
vm.inspection.icon = None vm.inspection.icon = None
return None return None

View File

@ -163,7 +163,7 @@ class vmmMediaCombo(vmmGObjectUI):
def reset_state(self): def reset_state(self):
try: try:
self._populate_media() self._populate_media()
except: except Exception:
logging.debug("Error populating mediadev combo", exc_info=True) logging.debug("Error populating mediadev combo", exc_info=True)
def get_path(self): def get_path(self):

View File

@ -62,7 +62,7 @@ class vmmNetworkList(vmmGObjectUI):
self.conn.disconnect_by_func(self._repopulate_network_list) self.conn.disconnect_by_func(self._repopulate_network_list)
self.conn.disconnect_by_func(self._repopulate_network_list) self.conn.disconnect_by_func(self._repopulate_network_list)
self.conn.disconnect_by_func(self._repopulate_network_list) self.conn.disconnect_by_func(self._repopulate_network_list)
except: except Exception:
pass pass
self.conn = None self.conn = None

View File

@ -110,7 +110,7 @@ def start_libvirtd():
try: try:
bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
except: except Exception:
logging.exception("Error getting system bus handle") logging.exception("Error getting system bus handle")
return return
@ -119,7 +119,7 @@ def start_libvirtd():
"org.freedesktop.systemd1", "org.freedesktop.systemd1",
"/org/freedesktop/systemd1", "/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager", None) "org.freedesktop.systemd1.Manager", None)
except: except Exception:
logging.exception("Couldn't connect to systemd") logging.exception("Couldn't connect to systemd")
return return
@ -134,7 +134,7 @@ def start_libvirtd():
if str(state).lower().strip("'") == "active": if str(state).lower().strip("'") == "active":
logging.debug("libvirtd already active, not starting") logging.debug("libvirtd already active, not starting")
return True return True
except: except Exception:
logging.exception("Failed to lookup libvirtd status") logging.exception("Failed to lookup libvirtd status")
return return
@ -150,5 +150,5 @@ def start_libvirtd():
time.sleep(2) time.sleep(2)
logging.debug("Starting libvirtd appeared to succeed") logging.debug("Starting libvirtd appeared to succeed")
return True return True
except: except Exception:
logging.exception("Failed to talk to system-config-services") logging.exception("Failed to talk to system-config-services")

View File

@ -238,7 +238,7 @@ class vmmPreferences(vmmGObjectUI):
for k in val.split(','): for k in val.split(','):
try: try:
key = int(k) key = int(k)
except: except Exception:
key = None key = None
if key is not None: if key is not None:

View File

@ -110,7 +110,7 @@ class LocalConsoleConnection(ConsoleConnection):
try: try:
if self.origtermios: if self.origtermios:
termios.tcsetattr(self.fd, termios.TCSANOW, self.origtermios) termios.tcsetattr(self.fd, termios.TCSANOW, self.origtermios)
except: except Exception:
# domain may already have exited, destroying the pty, so ignore # domain may already have exited, destroying the pty, so ignore
pass pass
@ -165,7 +165,7 @@ class LibvirtConsoleConnection(ConsoleConnection):
if events & libvirt.VIR_EVENT_HANDLE_READABLE: if events & libvirt.VIR_EVENT_HANDLE_READABLE:
try: try:
got = self.stream.recv(1024 * 100) got = self.stream.recv(1024 * 100)
except: except Exception:
logging.exception("Error receiving stream data") logging.exception("Error receiving stream data")
self.close() self.close()
return return
@ -188,7 +188,7 @@ class LibvirtConsoleConnection(ConsoleConnection):
try: try:
done = self.stream.send(self.terminalToStream) done = self.stream.send(self.terminalToStream)
except: except Exception:
logging.exception("Error sending stream data") logging.exception("Error sending stream data")
self.close() self.close()
return return
@ -233,11 +233,11 @@ class LibvirtConsoleConnection(ConsoleConnection):
if self.stream: if self.stream:
try: try:
self.stream.eventRemoveCallback() self.stream.eventRemoveCallback()
except: except Exception:
logging.exception("Error removing stream callback") logging.exception("Error removing stream callback")
try: try:
self.stream.finish() self.stream.finish()
except: except Exception:
logging.exception("Error finishing stream") logging.exception("Error finishing stream")
self.stream = None self.stream = None
@ -416,7 +416,7 @@ class vmmSerialConsole(vmmGObject):
self.show_error(_("Error connecting to text console: %s") % e) self.show_error(_("Error connecting to text console: %s") % e)
try: try:
self.console.close() self.console.close()
except: except Exception:
pass pass
return False return False

View File

@ -192,7 +192,7 @@ class vmmSnapshotPage(vmmGObjectUI):
for snap in self.vm.list_snapshots(): for snap in self.vm.list_snapshots():
if name == snap.get_name(): if name == snap.get_name():
snaps.append(snap) snaps.append(snap)
except: except Exception:
pass pass
snaps = [] snaps = []
@ -406,7 +406,7 @@ class vmmSnapshotPage(vmmGObjectUI):
try: try:
if stream: if stream:
stream.finish() stream.finish()
except: except Exception:
pass pass
def _get_screenshot(self): def _get_screenshot(self):
@ -424,7 +424,7 @@ class vmmSnapshotPage(vmmGObjectUI):
# https://bugs.launchpad.net/qemu/+bug/1314293 # https://bugs.launchpad.net/qemu/+bug/1314293
self._take_screenshot() self._take_screenshot()
mime, sdata = self._take_screenshot() mime, sdata = self._take_screenshot()
except: except Exception:
logging.exception("Error taking screenshot") logging.exception("Error taking screenshot")
return return
@ -518,7 +518,7 @@ class vmmSnapshotPage(vmmGObjectUI):
filename = basesn + "." + _mime_to_ext(mime) filename = basesn + "." + _mime_to_ext(mime)
logging.debug("Writing screenshot to %s", filename) logging.debug("Writing screenshot to %s", filename)
open(filename, "wb").write(sndata) open(filename, "wb").write(sndata)
except: except Exception:
logging.exception("Error saving screenshot") logging.exception("Error saving screenshot")
def _create_new_snapshot(self): def _create_new_snapshot(self):

View File

@ -51,13 +51,13 @@ class ConnectionInfo(object):
def _is_listen_localhost(self, host=None): def _is_listen_localhost(self, host=None):
try: try:
return ipaddr.IPNetwork(host or self.gaddr).is_loopback return ipaddr.IPNetwork(host or self.gaddr).is_loopback
except: except Exception:
return False return False
def _is_listen_any(self): def _is_listen_any(self):
try: try:
return ipaddr.IPNetwork(self.gaddr).is_unspecified return ipaddr.IPNetwork(self.gaddr).is_unspecified
except: except Exception:
return False return False
def _is_listen_none(self): def _is_listen_none(self):
@ -180,7 +180,7 @@ class _Tunnel(object):
while True: while True:
try: try:
new = self._errfd.recv(1024) new = self._errfd.recv(1024)
except: except Exception:
break break
if not new: if not new:

View File

@ -123,7 +123,7 @@ class vmmStorageList(vmmGObjectUI):
self.conn.disconnect_by_func(self._conn_pool_count_changed) self.conn.disconnect_by_func(self._conn_pool_count_changed)
self.conn.disconnect_by_func(self._conn_pool_count_changed) self.conn.disconnect_by_func(self._conn_pool_count_changed)
self.conn.disconnect_by_func(self._conn_state_changed) self.conn.disconnect_by_func(self._conn_state_changed)
except: except Exception:
pass pass
self.conn = None self.conn = None
@ -384,7 +384,7 @@ class vmmStorageList(vmmGObjectUI):
try: try:
pool.disconnect_by_func(self._pool_changed) pool.disconnect_by_func(self._pool_changed)
pool.disconnect_by_func(self._pool_changed) pool.disconnect_by_func(self._pool_changed)
except: except Exception:
pass pass
pool.connect("state-changed", self._pool_changed) pool.connect("state-changed", self._pool_changed)
pool.connect("refreshed", self._pool_changed) pool.connect("refreshed", self._pool_changed)
@ -426,7 +426,7 @@ class vmmStorageList(vmmGObjectUI):
cap = str(vol.get_capacity()) cap = str(vol.get_capacity())
sizestr = vol.get_pretty_capacity() sizestr = vol.get_pretty_capacity()
fmt = vol.get_format() or "" fmt = vol.get_format() or ""
except: except Exception:
logging.debug("Error getting volume info for '%s', " logging.debug("Error getting volume info for '%s', "
"hiding it", key, exc_info=True) "hiding it", key, exc_info=True)
continue continue
@ -439,7 +439,7 @@ class vmmStorageList(vmmGObjectUI):
namestr = ", ".join(names) namestr = ", ".join(names)
if not namestr: if not namestr:
namestr = None namestr = None
except: except Exception:
logging.exception("Failed to determine if storage volume in " logging.exception("Failed to determine if storage volume in "
"use.") "use.")

View File

@ -31,7 +31,7 @@ try:
# pylint: disable=no-name-in-module # pylint: disable=no-name-in-module
# pylint: disable=wrong-import-order # pylint: disable=wrong-import-order
from gi.repository import AppIndicator3 from gi.repository import AppIndicator3
except: except Exception:
AppIndicator3 = None AppIndicator3 = None

View File

@ -35,7 +35,7 @@ def spin_get_helper(widget):
try: try:
return int(txt) return int(txt)
except: except Exception:
return adj.get_value() return adj.get_value()

View File

@ -412,7 +412,7 @@ class VNCViewer(Viewer):
try: try:
keys = [int(k) for k in keys.split(',')] keys = [int(k) for k in keys.split(',')]
except: except Exception:
logging.debug("Error in grab_keys configuration in Gsettings", logging.debug("Error in grab_keys configuration in Gsettings",
exc_info=True) exc_info=True)
return return
@ -551,7 +551,7 @@ class SpiceViewer(Viewer):
autoredir = self.config.get_auto_redirection() autoredir = self.config.get_auto_redirection()
if autoredir: if autoredir:
gtk_session.set_property("auto-usbredir", True) gtk_session.set_property("auto-usbredir", True)
except: except Exception:
self._usbdev_manager = None self._usbdev_manager = None
logging.debug("Error initializing spice usb device manager", logging.debug("Error initializing spice usb device manager",
exc_info=True) exc_info=True)
@ -678,7 +678,7 @@ class SpiceViewer(Viewer):
try: try:
keys = [int(k) for k in keys.split(',')] keys = [int(k) for k in keys.split(',')]
except: except Exception:
logging.debug("Error in grab_keys configuration in Gsettings", logging.debug("Error in grab_keys configuration in Gsettings",
exc_info=True) exc_info=True)
return return

View File

@ -185,7 +185,7 @@ def _find_input(input_file, parser, print_cb):
return path, p, force_clean return path, p, force_clean
raise RuntimeError("Could not find parser for file %s" % input_file) raise RuntimeError("Could not find parser for file %s" % input_file)
except: except Exception:
for f in force_clean: for f in force_clean:
shutil.rmtree(f) shutil.rmtree(f)
raise raise

View File

@ -115,7 +115,7 @@ def parse_vmdk(filename):
try: try:
vmdkfile = _VMXFile(content) vmdkfile = _VMXFile(content)
except: except Exception:
logging.exception("%s looked like a vmdk file, but parsing failed", logging.exception("%s looked like a vmdk file, but parsing failed",
filename) filename)
return return

View File

@ -26,7 +26,7 @@ def _setup_i18n():
try: try:
locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, '')
except: except Exception:
# Can happen if user passed a bogus LANG # Can happen if user passed a bogus LANG
pass pass

View File

@ -131,7 +131,7 @@ class VirtStreamHandler(logging.StreamHandler):
self.flush() self.flush()
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
raise raise
except: except Exception:
self.handleError(record) self.handleError(record)
@ -158,7 +158,7 @@ class VirtHelpFormatter(argparse.RawDescriptionHelpFormatter):
if "\n" in text: if "\n" in text:
return text.splitlines() return text.splitlines()
return return_default() return return_default()
except: except Exception:
return return_default() return return_default()

View File

@ -186,7 +186,7 @@ class VirtualDisk(VirtualDevice):
if not conn.is_remote(): if not conn.is_remote():
return os.path.exists(path) return os.path.exists(path)
except: except Exception:
pass pass
return False return False
@ -257,7 +257,7 @@ class VirtualDisk(VirtualDevice):
int(label.split(":")[0].replace("+", ""))) int(label.split(":")[0].replace("+", "")))
if pwuid: if pwuid:
user = pwuid[0] user = pwuid[0]
except: except Exception:
logging.debug("Exception grabbing qemu DAC user", exc_info=True) logging.debug("Exception grabbing qemu DAC user", exc_info=True)
return None, [] return None, []
@ -308,7 +308,7 @@ class VirtualDisk(VirtualDevice):
try: try:
try: try:
fix_perms(dirname, useacl) fix_perms(dirname, useacl)
except: except Exception:
# If acl fails, fall back to chmod and retry # If acl fails, fall back to chmod and retry
if not useacl: if not useacl:
raise raise

View File

@ -90,7 +90,7 @@ class VirtualHostDevice(VirtualDevice):
def safeint(val, fmt="%.3d"): def safeint(val, fmt="%.3d"):
try: try:
int(val) int(val)
except: except Exception:
return str(val) return str(val)
return fmt % int(val) return fmt % int(val)

View File

@ -95,7 +95,7 @@ def _default_bridge(conn):
# vif0.0 == netloop enslaved, eth0 == default route # vif0.0 == netloop enslaved, eth0 == default route
try: try:
defn = int(dev[-1]) defn = int(dev[-1])
except: except Exception:
defn = -1 defn = -1
if (defn >= 0 and if (defn >= 0 and

View File

@ -89,7 +89,7 @@ def _stat_disk(path):
# os.SEEK_END is not present on all systems # os.SEEK_END is not present on all systems
size = os.lseek(fd, 0, 2) size = os.lseek(fd, 0, 2)
os.close(fd) os.close(fd)
except: except Exception:
size = 0 size = 0
return False, size return False, size
elif stat.S_ISREG(mode): elif stat.S_ISREG(mode):
@ -121,7 +121,7 @@ def check_if_path_managed(conn, path):
if verr: if verr:
try: try:
vol = _lookup_vol_by_basename(pool, path) vol = _lookup_vol_by_basename(pool, path)
except: except Exception:
pass pass
except Exception as e: except Exception as e:
vol = None vol = None

View File

@ -277,7 +277,7 @@ class DistroInstaller(Installer):
"remote connection.") "remote connection.")
else: else:
distro = OSDB.lookup_os_by_media(self.location) distro = OSDB.lookup_os_by_media(self.location)
except: except Exception:
logging.debug("Error attempting to detect distro.", exc_info=True) logging.debug("Error attempting to detect distro.", exc_info=True)
logging.debug("installer.detect_distro returned=%s", distro) logging.debug("installer.detect_distro returned=%s", distro)

View File

@ -85,7 +85,7 @@ class DomainCapabilities(XMLBuilder):
try: try:
xml = conn.getDomainCapabilities(emulator, arch, xml = conn.getDomainCapabilities(emulator, arch,
machine, hvtype) machine, hvtype)
except: except Exception:
logging.debug("Error fetching domcapabilities XML", logging.debug("Error fetching domcapabilities XML",
exc_info=True) exc_info=True)

View File

@ -98,7 +98,7 @@ class Guest(XMLBuilder):
try: try:
conn.lookupByName(name) conn.lookupByName(name)
except: except Exception:
return return
raise ValueError(_("Guest name '%s' is already in use.") % name) raise ValueError(_("Guest name '%s' is already in use.") % name)
@ -323,7 +323,7 @@ class Guest(XMLBuilder):
data = (self.os, self.on_reboot) data = (self.os, self.on_reboot)
try: try:
self._propstore["os"] = self.os.copy() self._propstore["os"] = self.os.copy()
except: except Exception:
self._finish_get_xml(data) self._finish_get_xml(data)
raise raise
return data return data
@ -397,12 +397,12 @@ class Guest(XMLBuilder):
# Handle undefining the VM if the initial startup fails # Handle undefining the VM if the initial startup fails
try: try:
domain.create() domain.create()
except: except Exception:
import sys import sys
exc_info = sys.exc_info() exc_info = sys.exc_info()
try: try:
domain.undefine() domain.undefine()
except: except Exception:
pass pass
raise exc_info[0], exc_info[1], exc_info[2] raise exc_info[0], exc_info[1], exc_info[2]

View File

@ -31,7 +31,7 @@ def _rhel4_initrd_inject(initrd, injections):
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
if "ext2 filesystem" not in file_proc.communicate()[0]: if "ext2 filesystem" not in file_proc.communicate()[0]:
return False return False
except: except Exception:
logging.exception("Failed to file command for rhel4 initrd detection") logging.exception("Failed to file command for rhel4 initrd detection")
return False return False

View File

@ -198,7 +198,7 @@ class Installer(object):
self.cleanup() self.cleanup()
try: try:
self._prepare(guest, meter) self._prepare(guest, meter)
except: except Exception:
self.cleanup() self.cleanup()
raise raise

View File

@ -113,7 +113,7 @@ def _upload_file(conn, meter, destpool, src):
# Cleanup # Cleanup
stream.finish() stream.finish()
meter.end(size) meter.end(size)
except: except Exception:
if vol: if vol:
vol.delete(0) vol.delete(0)
raise raise

View File

@ -276,7 +276,7 @@ class Network(XMLBuilder):
net.create() net.create()
if autostart: if autostart:
net.setAutostart(autostart) net.setAutostart(autostart)
except: except Exception:
net.undefine() net.undefine()
raise raise

View File

@ -30,7 +30,7 @@ def _compare_int(nodedev_val, hostdev_val):
return int(val or '0x00', 16) return int(val or '0x00', 16)
else: else:
return int(val) return int(val)
except: except Exception:
return -1 return -1
nodedev_val = _intify(nodedev_val) nodedev_val = _intify(nodedev_val)
@ -375,7 +375,7 @@ def _AddressStringToHostdev(conn, addrstr):
hostdev.device = device hostdev.device = device
else: else:
raise RuntimeError("Unknown address type") raise RuntimeError("Unknown address type")
except: except Exception:
logging.debug("Error parsing node device string.", exc_info=True) logging.debug("Error parsing node device string.", exc_info=True)
raise raise

View File

@ -351,7 +351,7 @@ class _OsVariant(object):
for n in t: for n in t:
new_version = new_version + ("%.4i" % int(n)) new_version = new_version + ("%.4i" % int(n))
version = new_version version = new_version
except: except Exception:
pass pass
return "%s-%s" % (self.distro, version) return "%s-%s" % (self.distro, version)

View File

@ -105,7 +105,7 @@ def _old_poll_helper(origmap, typename,
for name in newActiveNames + newInactiveNames: for name in newActiveNames + newInactiveNames:
try: try:
check_obj(name) check_obj(name)
except: except Exception:
logging.exception("Couldn't fetch %s '%s'", typename, name) logging.exception("Couldn't fetch %s '%s'", typename, name)
return (origmap.values(), new.values(), current.values()) return (origmap.values(), new.values(), current.values())
@ -253,7 +253,7 @@ def _old_fetch_vms(backend, origmap, build_func):
connkey = vm.name() connkey = vm.name()
check_new(vm, connkey) check_new(vm, connkey)
except: except Exception:
logging.exception("Couldn't fetch domain id '%s'", _id) logging.exception("Couldn't fetch domain id '%s'", _id)
@ -269,7 +269,7 @@ def _old_fetch_vms(backend, origmap, build_func):
connkey = name connkey = name
check_new(vm, connkey) check_new(vm, connkey)
except: except Exception:
logging.exception("Couldn't fetch domain '%s'", name) logging.exception("Couldn't fetch domain '%s'", name)
return (origmap.values(), new.values(), current.values()) return (origmap.values(), new.values(), current.values())

View File

@ -262,7 +262,7 @@ class StoragePool(_StorageObject):
for pool in conn.fetch_all_pools(): for pool in conn.fetch_all_pools():
if pool.name == "default": if pool.name == "default":
return pool.target_path return pool.target_path
except: except Exception:
pass pass
if build: if build:
@ -868,7 +868,7 @@ class StorageVolume(_StorageObject):
vol = self.pool.storageVolLookupByName(self.name) vol = self.pool.storageVolLookupByName(self.name)
vol.info() vol.info()
break break
except: except Exception:
if time: # pylint: disable=using-constant-test if time: # pylint: disable=using-constant-test
# This 'if' check saves some noise from the test suite # This 'if' check saves some noise from the test suite
time.sleep(.2) time.sleep(.2)

View File

@ -195,7 +195,7 @@ class _HTTPURLFetcher(_URLFetcher):
response.raise_for_status() response.raise_for_status()
try: try:
size = int(response.headers.get('content-length')) size = int(response.headers.get('content-length'))
except: except Exception:
size = None size = None
return response, size return response, size
@ -244,7 +244,7 @@ class _FTPURLFetcher(_URLFetcher):
try: try:
self._ftp.quit() self._ftp.quit()
except: except Exception:
logging.debug("Error quitting ftp connection", exc_info=True) logging.debug("Error quitting ftp connection", exc_info=True)
self._ftp = None self._ftp = None
@ -330,7 +330,7 @@ class _MountedURLFetcher(_LocalURLFetcher):
subprocess.call(cmd) subprocess.call(cmd)
try: try:
os.rmdir(self._srcdir) os.rmdir(self._srcdir)
except: except Exception:
pass pass
finally: finally:
self._mounted = False self._mounted = False
@ -664,7 +664,7 @@ class Distro(object):
try: try:
initrd = self.fetcher.acquireFile(initrdpath) initrd = self.fetcher.acquireFile(initrdpath)
return kernel, initrd, args return kernel, initrd, args
except: except Exception:
os.unlink(kernel) os.unlink(kernel)
raise raise
@ -874,7 +874,7 @@ class RHELDistro(RedHatDistro):
def _safeint(c): def _safeint(c):
try: try:
val = int(c) val = int(c)
except: except Exception:
val = 0 val = 0
return val return val

View File

@ -721,7 +721,7 @@ class _XMLState(object):
try: try:
doc = libxml2.parseDoc(parsexml) doc = libxml2.parseDoc(parsexml)
except: except Exception:
logging.debug("Error parsing xml=\n%s", parsexml) logging.debug("Error parsing xml=\n%s", parsexml)
raise raise