Skip to content

Commit b968417

Browse files
authored
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
1 parent 082c4bb commit b968417

3 files changed

Lines changed: 7 additions & 0 deletions

File tree

‎Lib/shutil.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1608,6 +1608,7 @@ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
16081608
path.
16091609
16101610
"""
1611+
cmd = os.fspath(cmd)
16111612
use_bytes = isinstance(cmd, bytes)
16121613

16131614
# If we're given a path with a directory part, look it up directly rather

‎Lib/test/test_shutil.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2614,6 +2614,10 @@ def test_basic(self):
26142614
rv = shutil.which(self.file, path=self.dir)
26152615
self.assertEqual(rv, self.filepath)
26162616

2617+
def test_pathlike_cmd(self):
2618+
rv = shutil.which(FakePath(self.file), path=self.dir)
2619+
self.assertEqual(rv, self.filepath)
2620+
26172621
def test_absolute_cmd(self):
26182622
# When given the fully qualified path to an executable that exists,
26192623
# it should be returned.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`shutil.which` for path-like command objects whose
2+
:meth:`~os.PathLike.__fspath__` method returns :class:`bytes`.

0 commit comments

Comments
 (0)