Align except clauses with PEP 3110 (#933)

This should work for Python 2.6+, including 3.
https://www.python.org/dev/peps/pep-3110/#compatibility-issues
This commit is contained in:
Elliot Jordan
2019-05-03 15:05:13 -07:00
committed by Greg Neagle
parent 270f23611e
commit 2ad27ff411
42 changed files with 208 additions and 208 deletions
+6 -6
View File
@@ -47,7 +47,7 @@ def copy_icon_to_repo(repo, name, path):
try:
repo.put_from_local_file(icon_ref, path)
print_utf8(u'\tWrote: %s' % icon_ref)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(u'\tError uploading %s: %s' % (icon_ref, unicode(err)))
@@ -61,7 +61,7 @@ def generate_png_from_startosinstall_item(repo, install_item):
dmg_temp = TempFile()
try:
repo.get_to_local_file(dmg_ref, dmg_temp.path)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(u'\tCan\'t download %s from repo: %s'
% (dmg_ref, unicode(err)))
return
@@ -97,7 +97,7 @@ def generate_png_from_dmg_item(repo, install_item):
dmg_temp = TempFile()
try:
repo.get_to_local_file(dmg_ref, dmg_temp.path)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(u'\tCan\'t download %s from repo: %s'
% (dmg_ref, unicode(err)))
return
@@ -134,7 +134,7 @@ def generate_pngs_from_pkg(repo, install_item):
file_temp = TempFile()
try:
repo.get_to_local_file(item_path, file_temp.path)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(u'\tCan\'t download %s from repo: %s'
% (item_path, unicode(err)))
return
@@ -189,7 +189,7 @@ def find_items_to_check(repo, itemlist=None):
try:
all_catalog_data = repo.get('catalogs/all')
catalogitems = FoundationPlist.readPlistFromString(all_catalog_data)
except (munkirepo.RepoError, FoundationPlist.FoundationPlistException), err:
except (munkirepo.RepoError, FoundationPlist.FoundationPlistException) as err:
print_err_utf8(
'Error getting catalog data from repo: %s' % unicode(err))
return []
@@ -267,7 +267,7 @@ def main():
# Make sure the repo exists
try:
repo = munkirepo.connect(options.repo_url, options.plugin)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(u'Could not connect to munki repo: %s' % unicode(err))
exit(-1)
+1 -1
View File
@@ -78,7 +78,7 @@ def main():
# Connect to the repo
try:
repo = munkirepo.connect(options.repo_url, options.plugin)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (u'Could not connect to munki repo: %s'
% unicode(err))
exit(-1)
+1 -1
View File
@@ -114,7 +114,7 @@ def main():
installeritem = None
try:
pkginfo = pkginfolib.makepkginfo(installeritem, options)
except pkginfolib.PkgInfoGenerationError, err:
except pkginfolib.PkgInfoGenerationError as err:
print >> sys.stderr, err
exit(-1)
+8 -8
View File
@@ -51,7 +51,7 @@ except ImportError:
print >> sys.stderr, _result, _stdout, _stderr
except utils.ScriptNotFoundError:
pass # script is not required, so pass
except utils.RunExternalScriptError, err:
except utils.RunExternalScriptError as err:
print >> sys.stderr, str(err)
sys.exit(200)
else:
@@ -183,12 +183,12 @@ def runScript(script, display_name, runtype):
try:
utils.verifyFileOnlyWritableByMunkiAndRoot(script)
except utils.VerifyFilePermissionsError, err:
except utils.VerifyFilePermissionsError as err:
# preflight/postflight is insecure, but if the currently executing
# file is insecure too we are no worse off.
try:
utils.verifyFileOnlyWritableByMunkiAndRoot(__file__)
except utils.VerifyFilePermissionsError, err:
except utils.VerifyFilePermissionsError as err:
# OK, managedsoftwareupdate is insecure anyway - warn & execute.
display.display_warning(
'Multiple munki executable scripts have insecure file '
@@ -213,7 +213,7 @@ def runScript(script, display_name, runtype):
display.display_info('%s stderr: %s' % (display_name, stderr))
except utils.ScriptNotFoundError:
pass # script is not required, so pass
except utils.RunExternalScriptError, err:
except utils.RunExternalScriptError as err:
display.display_warning(unicode(err))
return result
@@ -658,7 +658,7 @@ def main():
bootstrapping.set_bootstrap_mode()
print 'Bootstrap mode is set.'
exit(0)
except bootstrapping.SetupError, err:
except bootstrapping.SetupError as err:
print >> sys.stderr, err
exit(-1)
@@ -667,7 +667,7 @@ def main():
bootstrapping.clear_bootstrap_mode()
print 'Bootstrap mode cleared.'
exit(0)
except bootstrapping.SetupError, err:
except bootstrapping.SetupError as err:
print >> sys.stderr, err
exit(-1)
@@ -1066,7 +1066,7 @@ def main():
# so we'll stop running at startup/logout
try:
bootstrapping.clear_bootstrap_mode()
except bootstrapping.SetupError, err:
except bootstrapping.SetupError as err:
display.display_error(err)
display.display_status_major('Finishing...')
@@ -1132,7 +1132,7 @@ def main():
'clearing bootstrap mode to prevent relaunch')
try:
bootstrapping.clear_bootstrap_mode()
except bootstrapping.SetupError, err:
except bootstrapping.SetupError as err:
display.display_error(err)
+27 -27
View File
@@ -47,7 +47,7 @@ def get_installer_item_names(repo, catalog_limit_list):
item_list = []
try:
catalogs_list = repo.itemlist('catalogs')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (
'Could not retrieve catalogs: %s' % unicode(err))
return []
@@ -56,7 +56,7 @@ def get_installer_item_names(repo, catalog_limit_list):
try:
data = repo.get(os.path.join('catalogs', catalog_name))
catalog = plistlib.readPlistFromString(data)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (
'Could not retrieve catalog %s: %s'
% (catalog_name, unicode(err)))
@@ -77,7 +77,7 @@ def get_manifest_names(repo):
'''Returns a list of available manifests'''
try:
manifest_names = repo.itemlist('manifests')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (
'Could not retrieve manifests: %s' % unicode(err))
manifest_names = []
@@ -89,7 +89,7 @@ def get_catalogs(repo):
'''Returns a list of available catalogs'''
try:
catalog_names = repo.itemlist('catalogs')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (
'Could not retrieve catalogs: %s' % unicode(err))
catalog_names = []
@@ -143,11 +143,11 @@ def get_manifest(repo, manifest_name):
try:
data = repo.get(manifest_ref)
return plistlib.readPlistFromString(data)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (u'Could not retrieve manifest %s: %s'
% (manifest_name, unicode(err)))
return None
except (IOError, OSError, ExpatError), err:
except (IOError, OSError, ExpatError) as err:
print >> sys.stderr, (
u'Could not read manifest %s: %s' % (manifest_name, unicode(err)))
return None
@@ -165,7 +165,7 @@ def save_manifest(repo, manifest_dict, manifest_name, overwrite_existing=False):
data = plistlib.writePlistToString(manifest_dict)
repo.put(manifest_ref, data)
return True
except (IOError, OSError, ExpatError, munkirepo.RepoError), err:
except (IOError, OSError, ExpatError, munkirepo.RepoError) as err:
print >> sys.stderr, (
u'Saving %s failed: %s' % (manifest_name, unicode(err)))
return False
@@ -188,7 +188,7 @@ def manifest_rename(repo, source_manifest_name, dest_manifest_name,
repo.put(dest_manifest_ref, source_data)
repo.delete(source_manifest_ref)
return True
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, u'Renaming %s to %s failed: %s' % (
source_manifest_name, dest_manifest_name, unicode(err))
return False
@@ -276,7 +276,7 @@ def list_catalogs(repo, args):
Prints the names of the available catalogs''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -297,7 +297,7 @@ def list_catalog_items(repo, args):
Lists items in the given catalogs''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -324,7 +324,7 @@ def list_manifests(repo, args):
Prints names of available manifests.''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -356,7 +356,7 @@ def find(repo, args):
'FIND_TEXT'))
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -377,7 +377,7 @@ def find(repo, args):
try:
data = repo.get(manifest_ref)
manifest = plistlib.readPlistFromString(data)
except (IOError, OSError, ExpatError, munkirepo.RepoError), err:
except (IOError, OSError, ExpatError, munkirepo.RepoError) as err:
print >> sys.stderr, (
u'Error reading %s: %s' % (manifest_ref, unicode(err)))
continue
@@ -421,7 +421,7 @@ def display_manifest(repo, args):
Prints the contents of the specified manifest''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -460,7 +460,7 @@ def expand_included_manifests(repo, args):
Prints included manifests in the specified manifest''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -484,7 +484,7 @@ def new_manifest(repo, args):
Creates a new empty manifest''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -513,7 +513,7 @@ def copy_manifest(repo, args):
Copies the contents of one manifest to another''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -540,7 +540,7 @@ def rename_manifest(repo, args):
Renames the manifest''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -577,7 +577,7 @@ def add_pkg(repo, args):
'Defaults to managed_installs.'))
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -635,7 +635,7 @@ def move_install_to_uninstall(repo, args):
help='''name of manifest on which to operate''')
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -697,7 +697,7 @@ def remove_pkg(repo, args):
'package. Defaults to managed_installs.'))
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -748,7 +748,7 @@ def add_catalog(repo, args):
help='name of manifest on which to operate')
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -804,7 +804,7 @@ def remove_catalog(repo, args):
help='name of manifest on which to operate')
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -852,7 +852,7 @@ def add_included_manifest(repo, args):
help='name of manifest on which to operate')
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -912,7 +912,7 @@ def remove_included_manifest(repo, args):
help='name of manifest on which to operate')
try:
options, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -957,7 +957,7 @@ def refresh_cache(repo, args):
Refreshes the repo data''')
try:
_, arguments = parser.parse_args(args)
except MyOptParseError, errmsg:
except MyOptParseError as errmsg:
print >> sys.stderr, str(errmsg)
return 22 # Invalid argument
except MyOptParseExit:
@@ -1075,7 +1075,7 @@ def connect_to_repo():
exit(-1)
try:
repo = munkirepo.connect(repo_url, repo_plugin)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, u'Repo error: %s' % unicode(err)
exit(-1)
return repo
+11 -11
View File
@@ -89,7 +89,7 @@ def edit_pkginfo_in_editor(pkginfo):
os.close(filedesc)
try:
FoundationPlist.writePlist(pkginfo, filepath)
except FoundationPlist.FoundationPlistException, err:
except FoundationPlist.FoundationPlistException as err:
print >> sys.stderr, (
u'Could not save pkginfo to temp file: %s'
% unicode(err))
@@ -101,7 +101,7 @@ def edit_pkginfo_in_editor(pkginfo):
cmd = [editor, filepath]
try:
dummy_returncode = subprocess.check_call(cmd)
except (OSError, subprocess.CalledProcessError), err:
except (OSError, subprocess.CalledProcessError) as err:
print >> sys.stderr, (
'Problem running editor %s: %s.' % (editor, err))
os.remove(filepath)
@@ -114,7 +114,7 @@ def edit_pkginfo_in_editor(pkginfo):
answer = raw_input('Pkginfo editing complete? [y/n]: ')
try:
edited_pkginfo = FoundationPlist.readPlist(filepath)
except FoundationPlist.FoundationPlistException, err:
except FoundationPlist.FoundationPlistException as err:
print >> sys.stderr, (
u'Problem reading edited pkginfo: %s' % unicode(err))
os.remove(filepath)
@@ -128,7 +128,7 @@ def prompt_for_subdirectory(repo, subdirectory):
"""Prompts the user for a subdirectory for the pkg and pkginfo"""
try:
pkgsinfo_list = munkiimportlib.list_items_of_kind(repo, 'pkgsinfo')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise munkiimportlib.RepoCopyError(
u'Unable to get list of current pkgsinfo: %s' % unicode(err))
# filter the list of pkgsinfo to a list of subdirectories
@@ -329,7 +329,7 @@ def main():
try:
repo = munkirepo.connect(options.repo_url, options.plugin)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (u'Could not connect to munki repo: %s'
% unicode(err))
exit(-1)
@@ -382,7 +382,7 @@ def main():
# make a pkginfo!
try:
pkginfo = pkginfolib.makepkginfo(installer_item, options)
except pkginfolib.PkgInfoGenerationError, err:
except pkginfolib.PkgInfoGenerationError as err:
# makepkginfo returned an error
print >> sys.stderr, 'Getting package info failed.'
print >> sys.stderr, err
@@ -521,7 +521,7 @@ def main():
try:
munkiimportlib.convert_and_install_icon(repo, pkginfo,
options.icon_path)
except munkiimportlib.RepoCopyError, err:
except munkiimportlib.RepoCopyError as err:
print >> sys.stderr, err
elif options.extract_icon:
pass
@@ -543,7 +543,7 @@ def main():
print 'Imported %s.' % imported_paths
else:
print 'No icons found for import.'
except munkiimportlib.RepoCopyError, err:
except munkiimportlib.RepoCopyError as err:
print >> sys.stderr, err
# fix in case user accidentally starts subdirectory with a slash
@@ -558,7 +558,7 @@ def main():
options.subdirectory)
print 'Copied %s to %s.' % (os.path.basename(installer_item),
uploaded_pkgpath)
except munkiimportlib.RepoCopyError, errmsg:
except munkiimportlib.RepoCopyError as errmsg:
print >> sys.stderr, errmsg
cleanup_and_exit(-1)
@@ -575,7 +575,7 @@ def main():
options.subdirectory)
print 'Copied %s to %s.' % (
os.path.basename(uninstaller_item), uploaded_pkgpath)
except munkiimportlib.RepoCopyError, errmsg:
except munkiimportlib.RepoCopyError as errmsg:
print >> sys.stderr, errmsg
cleanup_and_exit(-1)
@@ -598,7 +598,7 @@ def main():
try:
pkginfo_path = munkiimportlib.copy_pkginfo_to_repo(repo, pkginfo, options.subdirectory)
print 'Saved pkginfo to %s.' % pkginfo_path
except munkiimportlib.RepoCopyError, errmsg:
except munkiimportlib.RepoCopyError as errmsg:
print >> sys.stderr, errmsg
cleanup_and_exit(-1)
+1 -1
View File
@@ -90,7 +90,7 @@ def readPlistFromString(data):
'''Read a plist data from a string. Return the root object.'''
try:
plistData = buffer(data)
except TypeError, err:
except TypeError as err:
raise NSPropertyListSerializationException(err)
dataObject, dummy_plistFormat, error = (
NSPropertyListSerialization.
@@ -53,11 +53,11 @@ def hash_icons(repo, output_fn=None):
try:
icondata = repo.get('icons/' + icon_ref)
icons[icon_ref] = hashlib.sha256(icondata).hexdigest()
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
errors.append(u'RepoError for %s: %s' % (icon_ref, unicode(err)))
except IOError, err:
except IOError as err:
errors.append(u'IO error for %s: %s' % (icon_ref, err))
except BaseException, err:
except BaseException as err:
errors.append(u'Unexpected error for %s: %s' % (icon_ref, err))
return icons, errors
@@ -165,7 +165,7 @@ def process_pkgsinfo(repo, options, output_fn=None):
output_fn("Getting list of pkgsinfo...")
try:
pkgsinfo_list = list_items_of_kind(repo, 'pkgsinfo')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise MakeCatalogsError(
"Error getting list of pkgsinfo items: %s" % unicode(err))
@@ -174,7 +174,7 @@ def process_pkgsinfo(repo, options, output_fn=None):
output_fn("Getting list of pkgs...")
try:
pkgs_list = list_items_of_kind(repo, 'pkgs')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise MakeCatalogsError(
"Error getting list of pkgs items: %s" % unicode(err))
@@ -188,10 +188,10 @@ def process_pkgsinfo(repo, options, output_fn=None):
try:
data = repo.get(pkginfo_ref)
pkginfo = plistlib.readPlistFromString(data)
except IOError, err:
except IOError as err:
errors.append("IO error for %s: %s" % (pkginfo_ref, err))
continue
except BaseException, err:
except BaseException as err:
errors.append("Unexpected error for %s: %s" % (pkginfo_ref, err))
continue
@@ -279,7 +279,7 @@ def makecatalogs(repo, options, output_fn=None):
repo.put(catalogpath, catalog_data)
if output_fn:
output_fn("Created %s..." % catalogpath)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
errors.append(
u'Failed to create catalog %s: %s' % (key, unicode(err)))
else:
@@ -292,7 +292,7 @@ def makecatalogs(repo, options, output_fn=None):
try:
repo.put(icon_hashes_plist, icon_hashes)
print "Created %s..." % (icon_hashes_plist)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
errors.append(
u'Failed to create %s: %s' % (icon_hashes_plist, unicode(err)))
+14 -14
View File
@@ -62,7 +62,7 @@ def copy_item_to_repo(repo, itempath, vers, subdirectory=''):
index = 0
try:
pkgs_list = list_items_of_kind(repo, 'pkgs')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Unable to get list of current pkgs: %s'
% unicode(err))
while destination_path_name in pkgs_list:
@@ -74,7 +74,7 @@ def copy_item_to_repo(repo, itempath, vers, subdirectory=''):
try:
repo.put_from_local_file(destination_path_name, itempath)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Unable to copy %s to %s: %s'
% (itempath, destination_path_name, unicode(err)))
else:
@@ -95,7 +95,7 @@ def copy_pkginfo_to_repo(repo, pkginfo, subdirectory=''):
index = 0
try:
pkgsinfo_list = list_items_of_kind(repo, 'pkgsinfo')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Unable to get list of current pkgsinfo: %s'
% unicode(err))
while pkginfo_path in pkgsinfo_list:
@@ -106,12 +106,12 @@ def copy_pkginfo_to_repo(repo, pkginfo, subdirectory=''):
try:
pkginfo_str = FoundationPlist.writePlistToString(pkginfo)
except FoundationPlist.NSPropertyListWriteException, errmsg:
except FoundationPlist.NSPropertyListWriteException as errmsg:
raise RepoCopyError(errmsg)
try:
repo.put(pkginfo_path, pkginfo_str)
return pkginfo_path
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError('Unable to save pkginfo to %s: %s'
% (pkginfo_path, unicode(err)))
@@ -136,12 +136,12 @@ def make_catalog_db(repo):
try:
plist = repo.get('catalogs/all')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise CatalogReadException(err)
try:
catalogitems = FoundationPlist.readPlistFromString(plist)
except FoundationPlist.NSPropertyListSerializationException, err:
except FoundationPlist.NSPropertyListSerializationException as err:
raise CatalogDecodeException(err)
pkgid_table = {}
@@ -238,7 +238,7 @@ def find_matching_pkginfo(repo, pkginfo):
try:
catdb = make_catalog_db(repo)
except CatalogReadException, err:
except CatalogReadException as err:
# could not retrieve catalogs/all
# do we have any existing pkgsinfo items?
pkgsinfo_items = repo.itemlist('pkgsinfo')
@@ -248,7 +248,7 @@ def find_matching_pkginfo(repo, pkginfo):
print (u'Could not get a list of existing items from the repo: %s'
% unicode(err))
return {}
except CatalogDBException, err:
except CatalogDBException as err:
# other error while processing catalogs/all
print (u'Could not get a list of existing items from the repo: %s'
% unicode(err))
@@ -330,7 +330,7 @@ def icon_exists_in_repo(repo, pkginfo):
icon_path = get_icon_path(pkginfo)
try:
icon_list = list_items_of_kind(repo, 'icons')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Unable to get list of current icons: %s'
% unicode(err))
if icon_path in icon_list:
@@ -453,7 +453,7 @@ def convert_and_install_icon(repo, pkginfo, icon_path, index=None):
try:
repo.put_from_local_file(repo_png_path, local_png_tmp)
return repo_png_path
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Error uploading icon to %s: %s'
% (repo_png_path, unicode(err)))
else:
@@ -468,21 +468,21 @@ def copy_icon_to_repo(repo, iconpath):
try:
icon_list = list_items_of_kind(repo, 'icons')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError(u'Unable to get list of current icons: %s'
% unicode(err))
if destination_path_name in icon_list:
# remove any existing icon in the repo
try:
repo.delete(destination_path_name)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError('Could not remove existing %s: %s'
% (destination_path_name, unicode(err)))
print 'Copying %s to %s...' % (icon_name, destination_path_name)
try:
repo.put_from_local_file(destination_path_name, iconpath)
return destination_path_name
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
raise RepoCopyError('Unable to copy %s to %s: %s'
% (iconpath, destination_path_name, unicode(err)))
+1 -1
View File
@@ -453,7 +453,7 @@ def makepkginfo(installeritem, options):
elif pkgutils.hasValidConfigProfileExt(installeritem):
try:
pkginfo = get_catalog_info_for_profile(installeritem)
except ProfileMetadataGenerationError, err:
except ProfileMetadataGenerationError as err:
print >> sys.stderr, err
raise PkgInfoGenerationError(
"%s doesn't appear to be a supported configuration "
+1 -1
View File
@@ -67,7 +67,7 @@ def rotate_pdapp_log():
newlogname = os.path.join(logdir, 'PDApp %s.log' % alternate_string)
try:
os.rename(pdapplog_path, newlogname)
except OSError, err:
except OSError as err:
munkilog.log('Could not rotate PDApp.log: %s', unicode(err))
+12 -12
View File
@@ -158,7 +158,7 @@ class ApplicationUsageRecorder(object):
try:
conn.execute(table_detection_sql)
exists = True
except sqlite3.OperationalError, err:
except sqlite3.OperationalError as err:
if err.args[0].startswith('no such table'):
exists = False
else:
@@ -291,7 +291,7 @@ class ApplicationUsageRecorder(object):
pass
# ok, done, hit an error
conn.close()
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error('Unhandled error reading existing db: %s', str(err))
return recovered
@@ -310,13 +310,13 @@ class ApplicationUsageRecorder(object):
conn.execute(table['insert_sql'], row)
conn.commit()
recovered += 1
except sqlite3.IntegrityError, err:
except sqlite3.IntegrityError as err:
logging.error(
'Ignored error: %s: %s', str(err), str(row))
self._close(conn)
os.unlink(APPLICATION_USAGE_DB)
os.rename(usage_db_tmp, APPLICATION_USAGE_DB)
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error('Unhandled error: %s', str(err))
recovered = 0
@@ -365,9 +365,9 @@ class ApplicationUsageRecorder(object):
self._create_application_usage_table(conn)
self._insert_application_usage(conn, event, app_dict)
conn.commit()
except sqlite3.OperationalError, err:
except sqlite3.OperationalError as err:
logging.error('Error writing %s event to database: %s', event, err)
except sqlite3.DatabaseError, err:
except sqlite3.DatabaseError as err:
if err.args[0] == 'database disk image is malformed':
self._recreate_database()
logging.error('Database error: %s', err)
@@ -398,9 +398,9 @@ class ApplicationUsageRecorder(object):
self._create_install_request_table(conn)
self._insert_install_request(conn, request_dict)
conn.commit()
except sqlite3.OperationalError, err:
except sqlite3.OperationalError as err:
logging.error('Error writing install request to database: %s', err)
except sqlite3.DatabaseError, err:
except sqlite3.DatabaseError as err:
if err.args[0] == 'database is malformed':
self._recreate_database()
logging.error('Database error: %s', err)
@@ -417,7 +417,7 @@ class ApplicationUsageQuery(object):
self.day_in_seconds = 24 * 60 * 60
try:
self.conn = sqlite3.connect(self.database)
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error(
'Error connecting to %s: %s', self.database, str(err))
self.conn = None
@@ -445,7 +445,7 @@ class ApplicationUsageQuery(object):
row = query.fetchone()
time_diff = int(time.time()) - int(row[0])
return int(time_diff/self.day_in_seconds)
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error(
'Error querying %s: %s', self.database, str(err))
return 0
@@ -473,7 +473,7 @@ class ApplicationUsageQuery(object):
return int(time_diff/self.day_in_seconds)
else:
return -1
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error(
'Error querying %s: %s', self.database, str(err))
return None
@@ -501,7 +501,7 @@ class ApplicationUsageQuery(object):
return int(time_diff/self.day_in_seconds)
else:
return -1
except sqlite3.Error, err:
except sqlite3.Error as err:
logging.error(
'Error querying %s: %s', self.database, str(err))
return None
+1 -1
View File
@@ -216,7 +216,7 @@ def parse_su_dist(filename):
display.display_error(
'Invalid XML in %s', filename)
return None
except IOError, err:
except IOError as err:
display.display_error(
'Error reading %s: %s', filename, err)
return None
+1 -1
View File
@@ -518,7 +518,7 @@ class AppleUpdateSync(object):
try:
return self.retrieve_url_to_cache_dir(
url, copy_only_if_missing=True)
except ReplicationError, err:
except ReplicationError as err:
display.display_error(
'Could not retrieve %s: %s', url, err)
return None
+2 -2
View File
@@ -104,7 +104,7 @@ def set_bootstrap_mode():
# create CHECKANDINSTALLATSTARTUPFLAG file
try:
open(constants.CHECKANDINSTALLATSTARTUPFLAG, 'w').close()
except (OSError, IOError), err:
except (OSError, IOError) as err:
reset_fde_autologin()
raise SetupError(
'Could not create bootstrapping flag file: %s', err)
@@ -116,6 +116,6 @@ def clear_bootstrap_mode():
if os.path.exists(constants.CHECKANDINSTALLATSTARTUPFLAG):
try:
os.unlink(constants.CHECKANDINSTALLATSTARTUPFLAG)
except OSError, err:
except OSError as err:
raise SetupError(
'Could not remove bootstrapping flag file: %s', err)
+10 -10
View File
@@ -269,7 +269,7 @@ def get_url(url, destinationpath,
# safely kill the connection then re-raise
connection.cancel()
raise
except Exception, err: # too general, I know
except Exception as err: # too general, I know
# Let us out! ... Safely! Unexpectedly quit dialogs are annoying...
connection.cancel()
# Re-raise the error as a GurlError
@@ -305,7 +305,7 @@ def get_url(url, destinationpath,
if str(connection.status).startswith('2') and temp_download_exists:
try:
os.rename(tempdownloadpath, destinationpath)
except OSError, err:
except OSError as err:
# Re-raise the error as a GurlError
raise GurlError(-1, str(err))
return connection.headers
@@ -460,7 +460,7 @@ def getFileIfChangedAtomically(path, destinationpath):
try:
if st_dst:
os.unlink(tmp_destinationpath)
except OSError, err:
except OSError as err:
if err.args[0] == errno.ENOENT:
pass # OK
else:
@@ -470,13 +470,13 @@ def getFileIfChangedAtomically(path, destinationpath):
# copy from source to temporary destination
try:
shutil.copy2(path, tmp_destinationpath)
except IOError, err:
except IOError as err:
raise FileCopyError('Copy IOError: %s' % str(err))
# rename temp destination to final destination
try:
os.rename(tmp_destinationpath, destinationpath)
except OSError, err:
except OSError as err:
raise FileCopyError('Renaming %s: %s' % (destinationpath, str(err)))
return True
@@ -517,11 +517,11 @@ def getHTTPfileIfChangedAtomically(url, destinationpath,
# them as GurlDownloadError
raise
except HTTPError, err:
except HTTPError as err:
err = 'HTTP result %s: %s' % tuple(err)
raise GurlDownloadError(err)
except GurlError, err:
except GurlError as err:
err = 'Error %s: %s' % tuple(err)
raise GurlDownloadError(err)
@@ -632,7 +632,7 @@ def getDataFromURL(url):
if os.path.exists(urldata):
try:
os.unlink(urldata)
except (IOError, OSError), err:
except (IOError, OSError) as err:
display.display_warning('Error in getDataFromURL: %s', err)
dummy_result = munki_resource(url, urldata)
try:
@@ -641,7 +641,7 @@ def getDataFromURL(url):
fdesc.close()
os.unlink(urldata)
return data
except (IOError, OSError), err:
except (IOError, OSError) as err:
display.display_warning('Error in getDataFromURL: %s', err)
return ''
@@ -671,7 +671,7 @@ def check_server(url):
try:
# attempt to get something at the url
dummy_data = getDataFromURL(url)
except ConnectionError, err:
except ConnectionError as err:
# err should contain a tuple with code and description
return (err[0], err[1])
except (GurlError, DownloadError):
+1 -1
View File
@@ -316,7 +316,7 @@ class Gurl(NSObject):
string = str(plistData)
try:
xattr.setxattr(self.destination_path, self.GURL_XATTR, string)
except IOError, err:
except IOError as err:
self.log('Could not store metadata to %s: %s'
% (self.destination_path, err))
+4 -4
View File
@@ -608,7 +608,7 @@ def available_disk_space(volumepath='/'):
volumepath = '/'
try:
stat_val = os.statvfs(volumepath)
except OSError, err:
except OSError as err:
display.display_error(
'Error getting disk space in %s: %s', volumepath, str(err))
return 0
@@ -689,7 +689,7 @@ def get_conditions():
utils.runExternalScript(conditionalscriptpath))
except utils.ScriptNotFoundError:
pass # script is not required, so pass
except utils.RunExternalScriptError, err:
except utils.RunExternalScriptError as err:
print >> sys.stderr, unicode(err)
else:
# /usr/local/munki/conditions does not exist
@@ -727,7 +727,7 @@ def saveappdata():
app_inventory,
os.path.join(
prefs.pref('ManagedInstallDir'), 'ApplicationInventory.plist'))
except FoundationPlist.NSPropertyListSerializationException, err:
except FoundationPlist.NSPropertyListSerializationException as err:
display.display_warning(
'Unable to save inventory report: %s' % err)
@@ -810,7 +810,7 @@ def predicate_evaluates_as_true(predicate_string, additional_info=None):
info_object.update(additional_info)
try:
predicate = NSPredicate.predicateWithFormat_(predicate_string)
except BaseException, err:
except BaseException as err:
display.display_warning('%s', err)
# can't parse predicate, so return False
return False
+2 -2
View File
@@ -107,7 +107,7 @@ def remove_quarantine_from_item(some_path):
try:
if "com.apple.quarantine" in xattr.xattr(some_path).list():
xattr.xattr(some_path).remove("com.apple.quarantine")
except BaseException, err:
except BaseException as err:
display.display_warning(
"Error removing com.apple.quarantine from %s: %s", some_path, err)
@@ -210,7 +210,7 @@ def copy_items_from_mountpoint(mountpoint, itemlist):
if os.path.isdir(destination_path):
shutil.rmtree(destination_path)
os.rename(temp_destination_path, destination_path)
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_error("Error moving item to destination: %s" % err)
return -1
+1 -1
View File
@@ -149,7 +149,7 @@ def _run_installer(cmd, env_vars, packagename):
try:
job = launchd.Job(cmd, environment_vars=env_vars)
job.start()
except launchd.LaunchdJobException, err:
except launchd.LaunchdJobException as err:
display.display_error(
'Error with launchd job (%s): %s', cmd, str(err))
display.display_error('Can\'t run installer.')
+2 -2
View File
@@ -732,7 +732,7 @@ def remove_filesystem_items(removalpaths, forcedeletebundles):
# directory is empty
try:
os.rmdir(pathtoremove)
except (OSError, IOError), err:
except (OSError, IOError) as err:
msg = "Couldn't remove directory %s - %s" % (
pathtoremove, err)
display.display_error(msg)
@@ -770,7 +770,7 @@ def remove_filesystem_items(removalpaths, forcedeletebundles):
# not a directory, just unlink it
try:
os.remove(pathtoremove)
except (OSError, IOError), err:
except (OSError, IOError) as err:
msg = "Couldn't remove item %s: %s" % (pathtoremove, err)
display.display_error(msg)
removalerrors = removalerrors + "\n" + msg
+16 -16
View File
@@ -46,7 +46,7 @@ def read_file(pathname):
data = fileobj.read()
fileobj.close()
return data
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_error(
'Could not read %s: %s', pathname, err)
return ''
@@ -60,7 +60,7 @@ def write_file(stringdata, pathname):
fileobject.write(stringdata)
fileobject.close()
return pathname
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_error(
'Couldn\'t write %s to %s: %s', stringdata, pathname, err)
return ''
@@ -84,7 +84,7 @@ def pem_cert_sha1_digest(cert_path):
try:
raw_bytes = pem_cert_bytes(cert_path)
return hashlib.sha1(raw_bytes).hexdigest().upper()
except BaseException, err:
except BaseException as err:
display.display_error('Error reading %s: %s' % (cert_path, err))
return None
@@ -203,7 +203,7 @@ def add_ca_certs_to_system_keychain(cert_info=None):
'-k', system_keychain, cert)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not add CA cert %s into System keychain: %s', cert, err)
@@ -256,7 +256,7 @@ def make_client_keychain(cert_info=None):
'-p', keychain_pass, abs_keychain_path)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not create keychain %s: %s', abs_keychain_path, err)
if original_home:
@@ -292,7 +292,7 @@ def make_client_keychain(cert_info=None):
'import', client_cert_file, '-A', '-k', abs_keychain_path)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not import %s: %s', client_cert_file, err)
if combined_pem:
@@ -319,7 +319,7 @@ def make_client_keychain(cert_info=None):
default_keychain = [
x.strip().strip('"')
for x in output.split('\n') if x.strip()][0]
except SecurityError, err:
except SecurityError as err:
# error raised if there is no default
default_keychain = None
# Temporarily assign the default keychain to ours
@@ -330,7 +330,7 @@ def make_client_keychain(cert_info=None):
display.display_debug2(
'Attempting to set default keychain to %s resulted in: %s',
abs_keychain_path, output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not set default keychain to %s failed: %s'
% (abs_keychain_path, err))
@@ -346,7 +346,7 @@ def make_client_keychain(cert_info=None):
if output:
display.display_debug2(
'security set-identity-preference output: ' + output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Setting identity preference for %s failed: %s'
% (url, err))
@@ -390,7 +390,7 @@ def add_to_keychain_list(keychain_path):
if output:
display.display_debug2(output)
added_keychain = True
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not add keychain %s to keychain list: %s',
keychain_path, err)
@@ -418,7 +418,7 @@ def remove_from_keychain_list(keychain_path):
'list-keychains', '-d', 'user', '-s', *filtered_keychains)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not set new keychain list: %s', err)
@@ -432,14 +432,14 @@ def unlock_and_set_nonlocking(keychain_path):
'unlock-keychain', '-p', keychain_pass, keychain_path)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
# some problem unlocking the keychain.
display.display_error(
'Could not unlock %s: %s.', keychain_path, err)
# delete it
try:
os.unlink(keychain_path)
except OSError, err:
except OSError as err:
display.display_error(
'Could not remove %s: %s.', keychain_path, err)
return
@@ -447,7 +447,7 @@ def unlock_and_set_nonlocking(keychain_path):
output = security('set-keychain-settings', keychain_path)
if output:
display.display_debug2(output)
except SecurityError, err:
except SecurityError as err:
display.display_error(
'Could not set keychain settings for %s: %s',
keychain_path, err)
@@ -495,7 +495,7 @@ def debug_output():
display.display_debug1('***Info for %s***' % keychainfile)
display.display_debug1(
security('show-keychain-info', keychainfile))
except SecurityError, err:
except SecurityError as err:
display.display_error(unicode(err))
@@ -558,7 +558,7 @@ class MunkiKeychain(object):
# we have client certs; we should build a keychain using them
try:
os.unlink(self.keychain_path)
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_error(
'Could not remove pre-existing %s: %s'
% (self.keychain_path, err))
+1 -1
View File
@@ -210,7 +210,7 @@ class Job(object):
# store their file descriptors for use
self.stdout = open(self.stdout_path, 'r')
self.stderr = open(self.stderr_path, 'r')
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise LaunchdJobException(err)
def stop(self):
+8 -8
View File
@@ -170,14 +170,14 @@ class FileRepo(Repo):
if NETFSMOUNTURLSYNC_AVAILABLE:
try:
self.root = mount_share_url(self.baseurl)
except ShareMountException, err:
except ShareMountException as err:
raise RepoError(err)
else:
self.we_mounted_repo = True
else:
try:
os.mkdir(self.root)
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(
u'Could not make repo mountpoint: %s' % unicode(err))
if self.baseurl.startswith('afp:'):
@@ -219,7 +219,7 @@ class FileRepo(Repo):
rel_path = abs_path[len(search_dir):].lstrip("/")
file_list.append(rel_path)
return file_list
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
def get(self, resource_identifier):
@@ -236,7 +236,7 @@ class FileRepo(Repo):
data = fileref.read()
fileref.close()
return data
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
def get_to_local_file(self, resource_identifier, local_file_path):
@@ -251,7 +251,7 @@ class FileRepo(Repo):
local_file_path = unicodeize(local_file_path)
try:
shutil.copyfile(repo_filepath, local_file_path)
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
def put(self, resource_identifier, content):
@@ -268,7 +268,7 @@ class FileRepo(Repo):
fileref = open(repo_filepath, 'w')
fileref.write(content)
fileref.close()
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
def put_from_local_file(self, resource_identifier, local_file_path):
@@ -287,7 +287,7 @@ class FileRepo(Repo):
os.makedirs(dir_path, 0755)
try:
shutil.copyfile(local_file_path, repo_filepath)
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
def delete(self, resource_identifier):
@@ -299,5 +299,5 @@ class FileRepo(Repo):
repo_filepath = os.path.join(self.root, resource_identifier)
try:
os.remove(repo_filepath)
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RepoError(err)
@@ -119,11 +119,11 @@ class MWA2APIRepo(Repo):
headers = {'Accept': 'application/xml'}
try:
data = self._curl(url, headers=headers)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
try:
plist = plistlib.readPlistFromString(data)
except ExpatError, err:
except ExpatError as err:
raise RepoError(err)
if kind in ['catalogs', 'manifests', 'pkgsinfo']:
# it's a list of dicts containing 'filename' key/values
@@ -147,7 +147,7 @@ class MWA2APIRepo(Repo):
headers = {}
try:
return self._curl(url, headers=headers)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
def get_to_local_file(self, resource_identifier, local_file_path):
@@ -165,7 +165,7 @@ class MWA2APIRepo(Repo):
headers = {}
try:
self._curl(url, headers=headers, filename=local_file_path)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
def put(self, resource_identifier, content):
@@ -181,7 +181,7 @@ class MWA2APIRepo(Repo):
headers = {}
try:
self._curl(url, headers=headers, method='PUT', content=content)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
def put_from_local_file(self, resource_identifier, local_file_path):
@@ -197,14 +197,14 @@ class MWA2APIRepo(Repo):
formdata = ['filedata=@%s' % local_file_path]
try:
self._curl(url, method='POST', formdata=formdata)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
else:
headers = {'Content-type': 'application/xml'}
try:
self._curl(url, headers=headers, method='PUT',
filename=local_file_path)
except CurlError, err:
except CurlError as err:
raise RepoError(err)
def delete(self, resource_identifier):
@@ -215,6 +215,6 @@ class MWA2APIRepo(Repo):
url = urllib2.quote(resource_identifier.encode('UTF-8'))
try:
self._curl(url, method='DELETE')
except CurlError, err:
except CurlError as err:
raise RepoError(err)
+2 -2
View File
@@ -139,7 +139,7 @@ class StartOSInstallRunner(object):
# set Munki to run at boot after the OS upgrade is complete
try:
bootstrapping.set_bootstrap_mode()
except bootstrapping.SetupError, err:
except bootstrapping.SetupError as err:
display.display_error(
'Could not set up Munki to run after OS upgrade is complete: '
'%s', err)
@@ -464,7 +464,7 @@ def startosinstall(installer, finishing_tasks=None, installinfo=None):
installer,
finishing_tasks=finishing_tasks, installinfo=installinfo).start()
return True
except StartOSInstallError, err:
except StartOSInstallError as err:
display.display_error(
u'Error starting macOS install: %s', unicode(err))
munkilog.log(
+1 -1
View File
@@ -68,7 +68,7 @@ def cleanUpTmpDir():
if hasattr(tmpdir, 'cache'):
try:
shutil.rmtree(tmpdir.cache)
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_warning(
'Unable to clean up temporary dir %s: %s',
tmpdir.cache, str(err))
+2 -2
View File
@@ -189,7 +189,7 @@ def force_logout_now():
except OSError:
pass
except BaseException, err:
except BaseException as err:
display.display_error('Exception in force_logout_now(): %s' % str(err))
@@ -211,7 +211,7 @@ def stop_requested():
display.display_info('### User stopped session ###')
try:
os.unlink(stop_request_flag)
except OSError, err:
except OSError as err:
display.display_error(
'Could not remove %s: %s', stop_request_flag, err)
return True
+4 -4
View File
@@ -62,7 +62,7 @@ def config_profile_info(ignore_cache=False):
try:
config_profile_info.cache = FoundationPlist.readPlist(
output_plist + '.plist')
except BaseException, err:
except BaseException as err:
display.display_error(
'Could not read configuration profile info: %s' % err)
config_profile_info.cache = {}
@@ -124,7 +124,7 @@ def store_profile_receipt_data(identifier, hash_value):
del profile_data[identifier]
try:
FoundationPlist.writePlist(profile_data, profile_receipt_data_path())
except BaseException, err:
except BaseException as err:
display.display_error(
'Cannot update hash for %s: %s' % (identifier, err))
@@ -136,7 +136,7 @@ def read_profile(profile_path):
except FoundationPlist.NSPropertyListSerializationException:
# possibly a signed profile
return read_signed_profile(profile_path)
except BaseException, err:
except BaseException as err:
display.display_error(
'Error reading profile %s: %s' % (profile_path, err))
return {}
@@ -165,7 +165,7 @@ def read_signed_profile(profile_path):
return {}
try:
return FoundationPlist.readPlistFromString(stdout)
except FoundationPlist.NSPropertyListSerializationException, err:
except FoundationPlist.NSPropertyListSerializationException as err:
# not a valid plist
display.display_error(
'Error reading profile %s: %s' % (profile_path, err))
+1 -1
View File
@@ -96,7 +96,7 @@ def run_script(itemname, path, scriptname, suppress_error=False):
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except OSError, err:
except OSError as err:
display.display_error(
'Error executing script %s: %s' % (scriptname, str(err)))
return -1
+3 -3
View File
@@ -555,7 +555,7 @@ def process_install(manifestitem, cataloglist, installinfo,
#if manifestitemname in installinfo['processed_installs']:
# installinfo['processed_installs'].remove(manifestitemname)
return False
except (fetch.GurlError, fetch.GurlDownloadError), errmsg:
except (fetch.GurlError, fetch.GurlDownloadError) as errmsg:
display.display_warning(
'Download of %s failed: %s', manifestitem, errmsg)
iteminfo['installed'] = False
@@ -568,7 +568,7 @@ def process_install(manifestitem, cataloglist, installinfo,
#if manifestitemname in installinfo['processed_installs']:
# installinfo['processed_installs'].remove(manifestitemname)
return False
except fetch.Error, errmsg:
except fetch.Error as errmsg:
display.display_warning(
'Can\'t install %s because: %s', manifestitemname, errmsg)
iteminfo['installed'] = False
@@ -980,7 +980,7 @@ def process_removal(manifestitem, cataloglist, installinfo):
'Can\'t uninstall %s because the integrity check '
'failed.', iteminfo['name'])
return False
except fetch.Error, errmsg:
except fetch.Error as errmsg:
display.display_warning(
'Failed to download the uninstaller for %s because %s',
iteminfo['name'], errmsg)
@@ -69,7 +69,7 @@ def guess_repo_url():
fetch.getDataFromURL(url + '/catalogs/all')
autodetected_url = url
break
except fetch.Error, err:
except fetch.Error as err:
# couldn't connect or other error
display.display_info('URL error: %s', err)
+1 -1
View File
@@ -449,7 +449,7 @@ def check(client_id='', localmanifestpath=None):
'Could not read InstallInfo.plist. Deleting...')
try:
os.unlink(installinfopath)
except OSError, err:
except OSError as err:
display.display_error(
'Failed to delete InstallInfo.plist: %s', str(err))
if oldinstallinfo == installinfo:
+10 -10
View File
@@ -248,7 +248,7 @@ def download_icons(item_list):
if not os.path.isdir(icon_subdir):
try:
os.makedirs(icon_subdir, 0755)
except OSError, err:
except OSError as err:
display.display_error('Could not create %s' % icon_subdir)
return
if server_icon_hash != local_hash:
@@ -265,7 +265,7 @@ def download_icons(item_list):
fetch.munki_resource(
icon_url, icon_path, message=message)
fetch.writeCachedChecksum(icon_path)
except fetch.Error, err:
except fetch.Error as err:
display.display_debug1(
'Error when retrieving icon %s from the server: %s',
icon_name, err)
@@ -302,7 +302,7 @@ def download_client_resources():
if not os.path.isdir(resource_dir):
try:
os.makedirs(resource_dir, 0755)
except OSError, err:
except OSError as err:
display.display_error(
'Could not create %s' % resource_dir)
return
@@ -317,7 +317,7 @@ def download_client_resources():
resource_url, resource_archive_path, message=message)
downloaded_resource_path = resource_archive_path
break
except fetch.Error, err:
except fetch.Error as err:
display.display_debug1(
'Could not retrieve client resources with name %s: %s',
filename, err)
@@ -326,7 +326,7 @@ def download_client_resources():
if os.path.exists(resource_archive_path):
try:
os.unlink(resource_archive_path)
except (OSError, IOError), err:
except (OSError, IOError) as err:
display.display_error(
'Could not remove stale %s: %s', resource_archive_path, err)
@@ -347,7 +347,7 @@ def download_catalog(catalogname):
try:
fetch.munki_resource(catalogurl, catalogpath, message=message)
return catalogpath
except fetch.Error, err:
except fetch.Error as err:
display.display_error(
'Could not retrieve catalog %s from server: %s',
catalogname, err)
@@ -384,7 +384,7 @@ def cache():
for item in _items_to_precache(install_info):
try:
download_installeritem(item, install_info, precaching=True)
except fetch.Error, err:
except fetch.Error as err:
display.display_warning(
'Failed to precache the installer for %s because %s',
item['name'], unicode(err))
@@ -416,7 +416,7 @@ def uncache(space_needed_in_kb):
item_path = os.path.join(cachedir, item[0])
try:
itemsize = int(os.path.getsize(item_path)/1024)
except OSError, err:
except OSError as err:
display.display_warning("Could not get size of %s: %s"
% (item_path, err))
itemsize = 0
@@ -447,7 +447,7 @@ def uncache(space_needed_in_kb):
try:
os.remove(item_path)
deleted_kb += item_size
except OSError, err:
except OSError as err:
display.display_error(
"Could not remove precached item %s: %s" % (item_path, err))
@@ -495,7 +495,7 @@ def stop_precaching_agent():
display.display_info("Stopping precaching agent")
try:
launchd.remove_job(PRECACHING_AGENT_LABEL)
except launchd.LaunchdJobException, err:
except launchd.LaunchdJobException as err:
display.display_error('Error stopping precaching agent: %s', err)
@@ -111,7 +111,7 @@ def installed_state(item_pl):
elif comparison == 2:
# this item is newer
foundnewer = True
except utils.Error, errmsg:
except utils.Error as errmsg:
# some problem with the installs data
display.display_error(unicode(errmsg))
# return 1 so we're marked as not needing to be installed
@@ -129,7 +129,7 @@ def installed_state(item_pl):
return 0
elif comparison == 2:
foundnewer = True
except utils.Error, errmsg:
except utils.Error as errmsg:
# some problem with the receipts data
display.display_error(unicode(errmsg))
# return 1 so we're marked as not needing to be installed
@@ -186,7 +186,7 @@ def some_version_installed(item_pl):
if compare.compare_item_version(item) == 0:
# not there
return False
except utils.Error, errmsg:
except utils.Error as errmsg:
# some problem with the installs data
display.display_error(unicode(errmsg))
return False
@@ -200,7 +200,7 @@ def some_version_installed(item_pl):
if compare.compare_receipt_version(item) == 0:
# not there
return False
except utils.Error, errmsg:
except utils.Error as errmsg:
# some problem with the installs data
display.display_error(unicode(errmsg))
return False
@@ -69,7 +69,7 @@ def update_available_license_seats(installinfo):
license_data = fetch.getDataFromURL(url)
display.display_debug1('Got: %s', license_data)
license_dict = FoundationPlist.readPlistFromString(license_data)
except fetch.Error, err:
except fetch.Error as err:
# problem fetching from URL
display.display_error('Error from %s: %s', url, err)
except FoundationPlist.FoundationPlistException:
@@ -98,7 +98,7 @@ def get_manifest(manifest_name, suppress_errors=False):
destinationdir = os.path.dirname(manifestpath)
try:
os.makedirs(destinationdir)
except OSError, err:
except OSError as err:
# OSError will be raised if destinationdir exists, ignore this case
if not os.path.isdir(destinationdir):
if not suppress_errors:
@@ -112,9 +112,9 @@ def get_manifest(manifest_name, suppress_errors=False):
try:
dummy_value = fetch.munki_resource(
manifesturl, manifestpath, message=message)
except fetch.ConnectionError, err:
except fetch.ConnectionError as err:
raise ManifestServerConnectionException(err)
except fetch.Error, err:
except fetch.Error as err:
if not suppress_errors:
display.display_error(
'Could not retrieve manifest %s from the server: %s',
@@ -249,7 +249,7 @@ def get_manifest_data(manifestpath):
if os.path.exists(manifestpath):
try:
os.unlink(manifestpath)
except OSError, err:
except OSError as err:
display.display_error(
'Failed to delete plist: %s', unicode(err))
else:
@@ -262,7 +262,7 @@ def get_manifest_value_for_key(manifestpath, keyname):
plist = get_manifest_data(manifestpath)
try:
return plist.get(keyname, None)
except AttributeError, err:
except AttributeError as err:
display.display_error(
'Failed to get manifest value for key: %s (%s)',
manifestpath, keyname)
@@ -284,7 +284,7 @@ def remove_from_selfserve_section(itemname, section):
return
try:
plist = FoundationPlist.readPlist(selfservemanifest)
except FoundationPlist.FoundationPlistException, err:
except FoundationPlist.FoundationPlistException as err:
# SelfServeManifest is broken, bail
display.display_debug1(
"Error reading %s: %s", selfservemanifest, err)
@@ -297,7 +297,7 @@ def remove_from_selfserve_section(itemname, section):
]
try:
FoundationPlist.writePlist(plist, selfservemanifest)
except FoundationPlist.FoundationPlistException, err:
except FoundationPlist.FoundationPlistException as err:
display.display_debug1(
"Error writing %s: %s", selfservemanifest, err)
+4 -4
View File
@@ -83,7 +83,7 @@ def verifyFileOnlyWritableByMunkiAndRoot(file_path):
"""
try:
file_stat = os.stat(file_path)
except OSError, err:
except OSError as err:
raise VerifyFilePermissionsError(
'%s does not exist. \n %s' % (file_path, str(err)))
@@ -103,7 +103,7 @@ def verifyFileOnlyWritableByMunkiAndRoot(file_path):
# verify other users cannot write to the file.
elif file_stat.st_mode & stat.S_IWOTH != 0:
raise InsecureFilePermissionsError('world writable!')
except InsecureFilePermissionsError, err:
except InsecureFilePermissionsError as err:
raise InsecureFilePermissionsError(
'%s is not secure! %s' % (file_path, err.args[0]))
@@ -127,7 +127,7 @@ def runExternalScript(script, allow_insecure=False, script_args=()):
if not allow_insecure:
try:
verifyFileOnlyWritableByMunkiAndRoot(script)
except VerifyFilePermissionsError, err:
except VerifyFilePermissionsError as err:
msg = ('Skipping execution due to failed file permissions '
'verification: %s\n%s' % (script, str(err)))
raise RunExternalScriptError(msg)
@@ -142,7 +142,7 @@ def runExternalScript(script, allow_insecure=False, script_args=()):
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except (OSError, IOError), err:
except (OSError, IOError) as err:
raise RunExternalScriptError(
'Error %s when attempting to run %s' % (unicode(err), script))
if proc:
+2 -2
View File
@@ -87,7 +87,7 @@ def PtyExec(argv):
if pid == 0: # child
try:
os.execv(argv[0], argv)
except OSError, e:
except OSError as e:
print >>sys.stderr, str(e)
sys.exit(1)
elif pid > 0: # parent
@@ -96,7 +96,7 @@ def PtyExec(argv):
while 1:
try:
(rl, wl, xl) = select.select([f], [], [], 5.0)
except select.error, e:
except select.error as e:
rl = []
if f in rl:
+8 -8
View File
@@ -118,7 +118,7 @@ class RepoCleaner(object):
# deleted
try:
manifests_list = self.repo.itemlist('manifests')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
self.errors.append(
"Repo error getting list of manifests: %s" % unicode(err))
manifests_list = []
@@ -126,7 +126,7 @@ class RepoCleaner(object):
try:
data = self.repo.get(os.path.join('manifests', manifest_name))
manifest = plistlib.readPlistFromString(data)
except (munkirepo.RepoError, IOError, OSError, ExpatError), err:
except (munkirepo.RepoError, IOError, OSError, ExpatError) as err:
self.errors.append("Unexpected error for %s: %s"
% (manifest_name, unicode(err)))
continue
@@ -155,7 +155,7 @@ class RepoCleaner(object):
print_utf8('Analyzing pkginfo files...')
try:
pkgsinfo_list = self.repo.itemlist('pkgsinfo')
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
self.errors.append(
"Repo error getting list of pkgsinfo: %s" % unicode(err))
pkgsinfo_list = []
@@ -165,7 +165,7 @@ class RepoCleaner(object):
try:
data = self.repo.get(pkginfo_identifier)
pkginfo = plistlib.readPlistFromString(data)
except (munkirepo.RepoError, IOError, OSError, ExpatError), err:
except (munkirepo.RepoError, IOError, OSError, ExpatError) as err:
self.errors.append("Unexpected error for %s: %s"
% (pkginfo_name, unicode(err)))
continue
@@ -331,7 +331,7 @@ class RepoCleaner(object):
print_utf8('Removing %s' % item['resource_identifier'])
try:
self.repo.delete(item['resource_identifier'])
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(unicode(err))
if (item.get('pkg_path') and
not item['pkg_path'] in self.pkgs_to_keep):
@@ -339,7 +339,7 @@ class RepoCleaner(object):
print_utf8('Removing %s' % pkg_to_remove)
try:
self.repo.delete(pkg_to_remove)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(unicode(err))
if (item.get('uninstallpkg_path') and
not item['uninstallpkg_path'] in self.pkgs_to_keep):
@@ -347,7 +347,7 @@ class RepoCleaner(object):
print_utf8('Removing %s' % pkg_to_remove)
try:
self.repo.delete(pkg_to_remove)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print_err_utf8(unicode(err))
def make_catalogs(self):
@@ -457,7 +457,7 @@ def main():
try:
repo = munkirepo.connect(options.repo_url, options.plugin)
except munkirepo.RepoError, err:
except munkirepo.RepoError as err:
print >> sys.stderr, (u'Could not connect to munki repo: %s'
% unicode(err))
exit(-1)
+7 -7
View File
@@ -134,7 +134,7 @@ class Supervisor(object):
stdout=stdout_pipe,
stderr=stderr_pipe,
)
except OSError, e:
except OSError as e:
self.exit_status = 127
raise ExecuteError(str(e))
@@ -193,7 +193,7 @@ class Supervisor(object):
logging.warning('Sending SIGKILL to %d', pid)
os.kill(-1 * pid, signal.SIGKILL)
time.sleep(KILL_WAIT_SECS)
except OSError, e:
except OSError as e:
if e.args[0] == errno.ESRCH:
logging.warning('pid %d died on its own')
else:
@@ -245,7 +245,7 @@ def parseOpts(argv):
'timeout=', 'delayrandom=', 'debug', 'help',
'error-exec=', 'error-exec-exit-codes=',
])
except getopt.GetoptError, e:
except getopt.GetoptError as e:
raise OptionError(str(e))
options = {}
@@ -335,7 +335,7 @@ def main(argv):
options, args = parseOpts(argv[1:])
if not processOpts(options, args):
return 0
except OptionError, e:
except OptionError as e:
logging.error(str(e))
return 1
@@ -345,7 +345,7 @@ def main(argv):
try:
sp = Supervisor(delayrandom_abort=True)
sp.setOptions(**options)
except Error, e:
except Error as e:
logging.exception('%s %s', e.__class__.__name__, str(e))
return 1
@@ -354,9 +354,9 @@ def main(argv):
try:
sp.execute(args)
ex = sp.getExitStatus()
except TimeoutError, e:
except TimeoutError as e:
ex = 1
except Error, e:
except Error as e:
logging.exception('%s %s', e.__class__.__name__, str(e))
ex = 1
+1 -1
View File
@@ -102,7 +102,7 @@ def AddHashesToPkginfoPlists(pkgsinfo_path, pkgs_path, update_existing=False):
# read plist
try:
plist = plistlib.readPlist(f_path)
except IOError, e:
except IOError as e:
print 'WARNING: pkginfo plist failed to open: %s\n%s' % (f_path,
str(e))
continue