gh-161788: Handle path-like commands in shutil.which() (#161789) Resolve command objects through the path protocol before selecting text or bytes handling. This preserves the documented bytes return type for path-like objects backed by bytes. Ref #161788
diff --git a/Lib/shutil.py b/Lib/shutil.py index c24b786..f6bc8e16 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 c0b48ea..1104552 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 0000000..21565e3 --- /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`.