diff --git a/Lib/shutil.py b/Lib/shutil.py index c24b786fb63924..f6bc8e16619e76 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -1608,6 +1608,7 @@ def which(cmd, mode=os.F_OK | os.X_OK, path=None): path. """ + cmd = os.fspath(cmd) use_bytes = isinstance(cmd, bytes) # If we're given a path with a directory part, look it up directly rather diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index c0b48ea306b71e..1104552215a44f 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -2614,6 +2614,10 @@ def test_basic(self): rv = shutil.which(self.file, path=self.dir) self.assertEqual(rv, self.filepath) + def test_pathlike_cmd(self): + rv = shutil.which(FakePath(self.file), path=self.dir) + self.assertEqual(rv, self.filepath) + def test_absolute_cmd(self): # When given the fully qualified path to an executable that exists, # it should be returned. diff --git a/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst b/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst new file mode 100644 index 00000000000000..21565e386cd3cc --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-10-23-51-25.gh-issue-161788.J8vQmK.rst @@ -0,0 +1,2 @@ +Fix :func:`shutil.which` for path-like command objects whose +:meth:`~os.PathLike.__fspath__` method returns :class:`bytes`.