From 8c61766b3e48d5401f20d49f150f6e311f1a7e5c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 10 Mar 2024 16:04:42 +0100 Subject: [PATCH] Fix ruff/bugbear issues (B904) B904 Within an `except` clause, raise exceptions with `raise ... from err` or `raise ... from None` to distinguish them from errors in exception handling https://docs.astral.sh/ruff/rules/raise-without-from-inside-except/ --- distutils/_msvccompiler.py | 16 ++++++++-------- distutils/archive_util.py | 8 ++++---- distutils/bcppcompiler.py | 10 +++++----- distutils/ccompiler.py | 16 +++++++++------- distutils/command/bdist.py | 8 ++++---- distutils/command/bdist_dumb.py | 4 ++-- distutils/command/build.py | 4 ++-- distutils/command/build_ext.py | 4 ++-- distutils/command/build_py.py | 4 ++-- distutils/command/build_scripts.py | 2 +- distutils/command/check.py | 2 +- distutils/command/install.py | 4 ++-- distutils/command/install_lib.py | 4 ++-- distutils/core.py | 12 +++++++----- distutils/cygwinccompiler.py | 8 ++++---- distutils/dir_util.py | 6 ++++-- distutils/dist.py | 8 ++++---- distutils/fancy_getopt.py | 2 +- distutils/file_util.py | 24 +++++++++++++++--------- distutils/msvc9compiler.py | 16 ++++++++-------- distutils/msvccompiler.py | 14 +++++++------- distutils/sysconfig.py | 4 ++-- distutils/tests/test_version.py | 2 +- distutils/unixccompiler.py | 8 ++++---- distutils/util.py | 2 +- distutils/zosccompiler.py | 2 +- 26 files changed, 103 insertions(+), 91 deletions(-) diff --git a/distutils/_msvccompiler.py b/distutils/_msvccompiler.py index a2159fef..a70ef8ec 100644 --- a/distutils/_msvccompiler.py +++ b/distutils/_msvccompiler.py @@ -149,7 +149,7 @@ def _get_vc_env(plat_spec): ).decode('utf-16le', errors='replace') except subprocess.CalledProcessError as exc: log.error(exc.output) - raise DistutilsPlatformError(f"Error executing {exc.cmd}") + raise DistutilsPlatformError(f"Error executing {exc.cmd}") from exc env = { key.lower(): value @@ -358,7 +358,7 @@ def compile( # noqa: C901 for obj in objects: try: src, ext = build[obj] - except KeyError: + except KeyError as e: continue if debug: # pass the full pathname to MSVC in debug mode, @@ -378,7 +378,7 @@ def compile( # noqa: C901 try: self.spawn([self.rc] + pp_opts + [output_opt, input_opt]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue elif ext in self._mc_extensions: # Compile .MC to .RC file to .RES file. @@ -403,11 +403,11 @@ def compile( # noqa: C901 self.spawn([self.rc, "/fo" + obj, rc_file]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue else: # how to handle this file? - raise CompileError(f"Don't know how to compile {src} to {obj}") + raise CompileError(f"Don't know how to compile {src} to {obj}") from e args = [self.cc] + compile_opts + pp_opts if add_cpp_opts: @@ -418,7 +418,7 @@ def compile( # noqa: C901 try: self.spawn(args) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg return objects @@ -438,7 +438,7 @@ def create_static_lib( log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args)) self.spawn([self.lib] + lib_args) except DistutilsExecError as msg: - raise LibError(msg) + raise LibError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -507,7 +507,7 @@ def link( log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args)) self.spawn([self.linker] + ld_args) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) diff --git a/distutils/archive_util.py b/distutils/archive_util.py index 052f6e46..3d61be5d 100644 --- a/distutils/archive_util.py +++ b/distutils/archive_util.py @@ -156,7 +156,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): # noqa: C901 try: spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) - except DistutilsExecError: + except DistutilsExecError as e: # XXX really should distinguish between "couldn't find # external 'zip' command" and "zip failed". raise DistutilsExecError( @@ -166,7 +166,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): # noqa: C901 "find a standalone zip utility" ) % zip_filename - ) + ) from e else: log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) @@ -259,8 +259,8 @@ def make_archive( try: format_info = ARCHIVE_FORMATS[format] - except KeyError: - raise ValueError("unknown archive format '%s'" % format) + except KeyError as e: + raise ValueError("unknown archive format '%s'" % format) from e func = format_info[0] for arg, val in format_info[1]: diff --git a/distutils/bcppcompiler.py b/distutils/bcppcompiler.py index c1341e43..a32164d3 100644 --- a/distutils/bcppcompiler.py +++ b/distutils/bcppcompiler.py @@ -125,7 +125,7 @@ def compile( # noqa: C901 try: self.spawn(["brcc32", "-fo", obj, src]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue # the 'for' loop # The next two are both for the real compiler. @@ -154,7 +154,7 @@ def compile( # noqa: C901 + [src] ) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg return objects @@ -173,7 +173,7 @@ def create_static_lib( try: self.spawn([self.lib] + lib_args) except DistutilsExecError as msg: - raise LibError(msg) + raise LibError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -304,7 +304,7 @@ def link( # noqa: C901 try: self.spawn([self.linker] + ld_args) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -392,6 +392,6 @@ def preprocess( self.spawn(pp_args) except DistutilsExecError as msg: print(msg) - raise CompileError(msg) + raise CompileError(msg) from msg # preprocess() diff --git a/distutils/ccompiler.py b/distutils/ccompiler.py index 8876d730..7501661b 100644 --- a/distutils/ccompiler.py +++ b/distutils/ccompiler.py @@ -969,8 +969,10 @@ def _make_out_path(self, output_dir, strip_dir, src_name): base = self._make_relative(base) try: new_ext = self.out_extensions[ext] - except LookupError: - raise UnknownFileError(f"unknown file type '{ext}' (from '{src_name}')") + except LookupError as e: + raise UnknownFileError( + f"unknown file type '{ext}' (from '{src_name}')" + ) from e if strip_dir: base = os.path.basename(base) return os.path.join(output_dir, base + new_ext) @@ -1144,22 +1146,22 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): compiler = get_default_compiler(plat) (module_name, class_name, long_description) = compiler_class[compiler] - except KeyError: + except KeyError as e: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler - raise DistutilsPlatformError(msg) + raise DistutilsPlatformError(msg) from e try: module_name = "distutils." + module_name __import__(module_name) module = sys.modules[module_name] klass = vars(module)[class_name] - except ImportError: + except ImportError as e: raise DistutilsModuleError( "can't compile C/C++ code: unable to load module '%s'" % module_name - ) - except KeyError: + ) from e + except KeyError as e: raise DistutilsModuleError( f"can't compile C/C++ code: unable to find class '{class_name}' " f"in module '{module_name}'" diff --git a/distutils/command/bdist.py b/distutils/command/bdist.py index ade98445..948f817f 100644 --- a/distutils/command/bdist.py +++ b/distutils/command/bdist.py @@ -117,11 +117,11 @@ def finalize_options(self): if self.formats is None: try: self.formats = [self.default_format[os.name]] - except KeyError: + except KeyError as e: raise DistutilsPlatformError( "don't know how to create built distributions " "on platform %s" % os.name - ) + ) from e if self.dist_dir is None: self.dist_dir = "dist" @@ -132,8 +132,8 @@ def run(self): for format in self.formats: try: commands.append(self.format_commands[format][0]) - except KeyError: - raise DistutilsOptionError("invalid format '%s'" % format) + except KeyError as e: + raise DistutilsOptionError("invalid format '%s'" % format) from e # Reinitialize and run each command. for i in range(len(self.formats)): diff --git a/distutils/command/bdist_dumb.py b/distutils/command/bdist_dumb.py index 06502d20..711bfad1 100644 --- a/distutils/command/bdist_dumb.py +++ b/distutils/command/bdist_dumb.py @@ -78,11 +78,11 @@ def finalize_options(self): if self.format is None: try: self.format = self.default_format[os.name] - except KeyError: + except KeyError as e: raise DistutilsPlatformError( "don't know how to create dumb built distributions " "on platform %s" % os.name - ) + ) from e self.set_undefined_options( 'bdist', diff --git a/distutils/command/build.py b/distutils/command/build.py index d18ed503..011ca75b 100644 --- a/distutils/command/build.py +++ b/distutils/command/build.py @@ -119,8 +119,8 @@ def finalize_options(self): # noqa: C901 if isinstance(self.parallel, str): try: self.parallel = int(self.parallel) - except ValueError: - raise DistutilsOptionError("parallel should be an integer") + except ValueError as e: + raise DistutilsOptionError("parallel should be an integer") from e def run(self): # Run all relevant sub-commands. This will be some subset of: diff --git a/distutils/command/build_ext.py b/distutils/command/build_ext.py index 06d949af..e5257fd3 100644 --- a/distutils/command/build_ext.py +++ b/distutils/command/build_ext.py @@ -289,8 +289,8 @@ def finalize_options(self): # noqa: C901 if isinstance(self.parallel, str): try: self.parallel = int(self.parallel) - except ValueError: - raise DistutilsOptionError("parallel should be an integer") + except ValueError as e: + raise DistutilsOptionError("parallel should be an integer") from e def run(self): # noqa: C901 from ..ccompiler import new_compiler diff --git a/distutils/command/build_py.py b/distutils/command/build_py.py index 56e6fa2e..1990100e 100644 --- a/distutils/command/build_py.py +++ b/distutils/command/build_py.py @@ -64,8 +64,8 @@ def finalize_options(self): try: self.optimize = int(self.optimize) assert 0 <= self.optimize <= 2 - except (ValueError, AssertionError): - raise DistutilsOptionError("optimize must be 0, 1, or 2") + except (ValueError, AssertionError) as e: + raise DistutilsOptionError("optimize must be 0, 1, or 2") from e def run(self): # XXX copy_file by default preserves atime and mtime. IMHO this is diff --git a/distutils/command/build_scripts.py b/distutils/command/build_scripts.py index 5f3902a0..f8e3c085 100644 --- a/distutils/command/build_scripts.py +++ b/distutils/command/build_scripts.py @@ -163,7 +163,7 @@ def _validate_shebang(shebang, encoding): # the script encoding too. try: shebang.encode(encoding) - except UnicodeEncodeError: + except UnicodeEncodeError as e: raise ValueError( f"The shebang ({shebang!r}) is not encodable " f"to the script encoding ({encoding})" diff --git a/distutils/command/check.py b/distutils/command/check.py index 28599e10..0598e569 100644 --- a/distutils/command/check.py +++ b/distutils/command/check.py @@ -81,7 +81,7 @@ def run(self): try: self.check_restructuredtext() except TypeError as exc: - raise DistutilsSetupError(str(exc)) + raise DistutilsSetupError(str(exc)) from exc elif self.strict: raise DistutilsSetupError('The docutils package is needed.') diff --git a/distutils/command/install.py b/distutils/command/install.py index 8e920be4..feebea48 100644 --- a/distutils/command/install.py +++ b/distutils/command/install.py @@ -598,10 +598,10 @@ def finalize_other(self): self.install_base = self.install_platbase = self.prefix try: self.select_scheme(os.name) - except KeyError: + except KeyError as e: raise DistutilsPlatformError( "I don't know how to install stuff on '%s'" % os.name - ) + ) from e def select_scheme(self, name): _select_scheme(self, name) diff --git a/distutils/command/install_lib.py b/distutils/command/install_lib.py index b1f346f0..8a1695ca 100644 --- a/distutils/command/install_lib.py +++ b/distutils/command/install_lib.py @@ -83,8 +83,8 @@ def finalize_options(self): self.optimize = int(self.optimize) if self.optimize not in (0, 1, 2): raise AssertionError - except (ValueError, AssertionError): - raise DistutilsOptionError("optimize must be 0, 1, or 2") + except (ValueError, AssertionError) as e: + raise DistutilsOptionError("optimize must be 0, 1, or 2") from e def run(self): # Make sure we have built everything we need first diff --git a/distutils/core.py b/distutils/core.py index 309ce696..3baebc35 100644 --- a/distutils/core.py +++ b/distutils/core.py @@ -146,9 +146,11 @@ class found in 'cmdclass' is used in place of the default, which is _setup_distribution = dist = klass(attrs) except DistutilsSetupError as msg: if 'name' not in attrs: - raise SystemExit("error in setup command: %s" % msg) + raise SystemExit("error in setup command: %s" % msg) from msg else: - raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg)) + raise SystemExit( + "error in {} setup command: {}".format(attrs['name'], msg) + ) from msg if _setup_stop_after == "init": return dist @@ -170,7 +172,7 @@ class found in 'cmdclass' is used in place of the default, which is try: ok = dist.parse_command_line() except DistutilsArgError as msg: - raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg) + raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg) from msg if DEBUG: print("options (after parsing command line):") @@ -205,13 +207,13 @@ def run_commands(dist): sys.stderr.write(f"error: {exc}\n") raise else: - raise SystemExit(f"error: {exc}") + raise SystemExit(f"error: {exc}") from exc except (DistutilsError, CCompilerError) as msg: if DEBUG: raise else: - raise SystemExit("error: " + str(msg)) + raise SystemExit("error: " + str(msg)) from msg return dist diff --git a/distutils/cygwinccompiler.py b/distutils/cygwinccompiler.py index 539f09d8..f643d6ad 100644 --- a/distutils/cygwinccompiler.py +++ b/distutils/cygwinccompiler.py @@ -60,8 +60,8 @@ def get_msvcr(): return try: return _msvcr_lookup[msc_ver] - except KeyError: - raise ValueError("Unknown MS Compiler version %s " % msc_ver) + except KeyError as e: + raise ValueError("Unknown MS Compiler version %s " % msc_ver) from e _runtime_library_dirs_msg = ( @@ -135,14 +135,14 @@ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): try: self.spawn(["windres", "-i", src, "-o", obj]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg else: # for other files use the C-compiler try: self.spawn( self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs ) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg def link( self, diff --git a/distutils/dir_util.py b/distutils/dir_util.py index 2021bed8..3337809a 100644 --- a/distutils/dir_util.py +++ b/distutils/dir_util.py @@ -76,7 +76,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901 if not (exc.errno == errno.EEXIST and os.path.isdir(head)): raise DistutilsFileError( f"could not create '{head}': {exc.args[-1]}" - ) + ) from exc created_dirs.append(head) _path_created[abs_head] = 1 @@ -142,7 +142,9 @@ def copy_tree( # noqa: C901 if dry_run: names = [] else: - raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}") + raise DistutilsFileError( + f"error listing files in '{src}': {e.strerror}" + ) from e if not dry_run: mkpath(dst, verbose=verbose) diff --git a/distutils/dist.py b/distutils/dist.py index f29a34fa..1290135c 100644 --- a/distutils/dist.py +++ b/distutils/dist.py @@ -425,7 +425,7 @@ def parse_config_files(self, filenames=None): # noqa: C901 else: setattr(self, opt, val) except ValueError as msg: - raise DistutilsOptionError(msg) + raise DistutilsOptionError(msg) from msg # -- Command-line parsing methods ---------------------------------- @@ -534,7 +534,7 @@ def _parse_command_opts(self, parser, args): # noqa: C901 try: cmd_class = self.get_command_class(command) except DistutilsModuleError as msg: - raise DistutilsArgError(msg) + raise DistutilsArgError(msg) from msg # Require that the command class be derived from Command -- want # to be sure that the basic "command" interface is implemented. @@ -834,7 +834,7 @@ def get_command_class(self, command): try: klass = getattr(module, klass_name) - except AttributeError: + except AttributeError as e: raise DistutilsModuleError( f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')" ) @@ -913,7 +913,7 @@ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 f"error in {source}: command '{command_name}' has no such option '{option}'" ) except ValueError as msg: - raise DistutilsOptionError(msg) + raise DistutilsOptionError(msg) from msg def reinitialize_command(self, command, reinit_subcommands=0): """Reinitializes a command to the state it was in when first diff --git a/distutils/fancy_getopt.py b/distutils/fancy_getopt.py index 1b54c891..efb6ab1c 100644 --- a/distutils/fancy_getopt.py +++ b/distutils/fancy_getopt.py @@ -244,7 +244,7 @@ def getopt(self, args=None, object=None): # noqa: C901 try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: - raise DistutilsArgError(msg) + raise DistutilsArgError(msg) from msg for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option diff --git a/distutils/file_util.py b/distutils/file_util.py index 960def9c..e42c836e 100644 --- a/distutils/file_util.py +++ b/distutils/file_util.py @@ -27,24 +27,28 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 try: fsrc = open(src, 'rb') except OSError as e: - raise DistutilsFileError(f"could not open '{src}': {e.strerror}") + raise DistutilsFileError(f"could not open '{src}': {e.strerror}") from e if os.path.exists(dst): try: os.unlink(dst) except OSError as e: - raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}") + raise DistutilsFileError( + f"could not delete '{dst}': {e.strerror}" + ) from e try: fdst = open(dst, 'wb') except OSError as e: - raise DistutilsFileError(f"could not create '{dst}': {e.strerror}") + raise DistutilsFileError(f"could not create '{dst}': {e.strerror}") from e while True: try: buf = fsrc.read(buffer_size) except OSError as e: - raise DistutilsFileError(f"could not read from '{src}': {e.strerror}") + raise DistutilsFileError( + f"could not read from '{src}': {e.strerror}" + ) from e if not buf: break @@ -52,7 +56,9 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 try: fdst.write(buf) except OSError as e: - raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}") + raise DistutilsFileError( + f"could not write to '{dst}': {e.strerror}" + ) from e finally: if fdst: fdst.close() @@ -122,8 +128,8 @@ def copy_file( # noqa: C901 try: action = _copy_action[link] - except KeyError: - raise ValueError("invalid value '%s' for 'link' argument" % link) + except KeyError as e: + raise ValueError("invalid value '%s' for 'link' argument" % link) from e if verbose >= 1: if os.path.basename(dst) == os.path.basename(src): @@ -208,7 +214,7 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901 if num == errno.EXDEV: copy_it = True else: - raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}") + raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}") from e if copy_it: copy_file(src, dst, verbose=verbose) @@ -218,7 +224,7 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901 (num, msg) = e.args try: os.unlink(dst) - except OSError: + except OSError as e: pass raise DistutilsFileError( f"couldn't move '{src}' to '{dst}' by copy/delete: " diff --git a/distutils/msvc9compiler.py b/distutils/msvc9compiler.py index 6a0105e4..0595d6b5 100644 --- a/distutils/msvc9compiler.py +++ b/distutils/msvc9compiler.py @@ -155,13 +155,13 @@ def load_macros(self, version): self.set_macro("FrameworkSDKDir", NET_BASE, "sdkinstallrootv2.0") else: raise KeyError("sdkinstallrootv2.0") - except KeyError: + except KeyError as e: raise DistutilsPlatformError( """Python was built with Visual Studio 2008; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2008 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""" - ) + ) from e if version >= 9.0: self.set_macro("FrameworkVersion", self.vsbase, "clr version") @@ -532,7 +532,7 @@ def compile( # noqa: C901 try: self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue elif ext in self._mc_extensions: # Compile .MC to .RC file to .RES file. @@ -557,7 +557,7 @@ def compile( # noqa: C901 self.spawn([self.rc] + ["/fo" + obj] + [rc_file]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue else: # how to handle this file? @@ -573,7 +573,7 @@ def compile( # noqa: C901 + extra_postargs ) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg return objects @@ -592,7 +592,7 @@ def create_static_lib( try: self.spawn([self.lib] + lib_args) except DistutilsExecError as msg: - raise LibError(msg) + raise LibError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -672,7 +672,7 @@ def link( # noqa: C901 try: self.spawn([self.linker] + ld_args) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg # embed the manifest # XXX - this is somewhat fragile - if mt.exe fails, distutils @@ -686,7 +686,7 @@ def link( # noqa: C901 try: self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg]) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) diff --git a/distutils/msvccompiler.py b/distutils/msvccompiler.py index ac8b68c0..5d78c320 100644 --- a/distutils/msvccompiler.py +++ b/distutils/msvccompiler.py @@ -145,13 +145,13 @@ def load_macros(self, version): self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") - except KeyError: + except KeyError as e: raise DistutilsPlatformError( """Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""" - ) + ) from e p = r"Software\Microsoft\NET Framework Setup\Product" for base in HKEYS: @@ -426,7 +426,7 @@ def compile( # noqa: C901 try: self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue elif ext in self._mc_extensions: # Compile .MC to .RC file to .RES file. @@ -451,7 +451,7 @@ def compile( # noqa: C901 self.spawn([self.rc] + ["/fo" + obj] + [rc_file]) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg continue else: # how to handle this file? @@ -467,7 +467,7 @@ def compile( # noqa: C901 + extra_postargs ) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg return objects @@ -486,7 +486,7 @@ def create_static_lib( try: self.spawn([self.lib] + lib_args) except DistutilsExecError as msg: - raise LibError(msg) + raise LibError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -565,7 +565,7 @@ def link( # noqa: C901 try: self.spawn([self.linker] + ld_args) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) diff --git a/distutils/sysconfig.py b/distutils/sysconfig.py index 1a38e9fa..269d0606 100644 --- a/distutils/sysconfig.py +++ b/distutils/sysconfig.py @@ -123,11 +123,11 @@ def get_python_inc(plat_specific=0, prefix=None): resolved_prefix = prefix if prefix is not None else default_prefix try: getter = globals()[f'_get_python_inc_{os.name}'] - except KeyError: + except KeyError as e: raise DistutilsPlatformError( "I don't know where Python installs its C header files " "on platform '%s'" % os.name - ) + ) from e return getter(resolved_prefix, prefix, plat_specific) diff --git a/distutils/tests/test_version.py b/distutils/tests/test_version.py index 1508e1cc..d9f8be74 100644 --- a/distutils/tests/test_version.py +++ b/distutils/tests/test_version.py @@ -44,7 +44,7 @@ def test_cmp_strict(self): for v1, v2, wanted in versions: try: res = StrictVersion(v1)._cmp(StrictVersion(v2)) - except ValueError: + except ValueError as e: if wanted is ValueError: continue else: diff --git a/distutils/unixccompiler.py b/distutils/unixccompiler.py index a1fe2b57..41db5b5c 100644 --- a/distutils/unixccompiler.py +++ b/distutils/unixccompiler.py @@ -177,14 +177,14 @@ def preprocess( try: self.spawn(pp_args) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs) try: self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg def create_static_lib( self, objects, output_libname, output_dir=None, debug=0, target_lang=None @@ -206,7 +206,7 @@ def create_static_lib( try: self.spawn(self.ranlib + [output_filename]) except DistutilsExecError as msg: - raise LibError(msg) + raise LibError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -265,7 +265,7 @@ def link( self.spawn(linker + ld_args) except DistutilsExecError as msg: - raise LinkError(msg) + raise LinkError(msg) from msg else: log.debug("skipping %s (up-to-date)", output_filename) diff --git a/distutils/util.py b/distutils/util.py index 9ee77721..c52317d6 100644 --- a/distutils/util.py +++ b/distutils/util.py @@ -204,7 +204,7 @@ def subst_vars(s, local_vars): try: return _subst_compat(s).format_map(lookup) except KeyError as var: - raise ValueError(f"invalid variable {var}") + raise ValueError(f"invalid variable {var}") from var def _subst_compat(s): diff --git a/distutils/zosccompiler.py b/distutils/zosccompiler.py index c7a7ca61..6e7c9f53 100644 --- a/distutils/zosccompiler.py +++ b/distutils/zosccompiler.py @@ -157,7 +157,7 @@ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): try: self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError as msg: - raise CompileError(msg) + raise CompileError(msg) from msg def runtime_library_dir_option(self, dir): return '-L' + dir