@@ -1279,6 +1279,15 @@ def get_terminal_size(fallback=(80, 24)):
12791279
12801280 return os .terminal_size ((columns , lines ))
12811281
1282+
1283+ # Check that a given file can be accessed with the correct mode.
1284+ # Additionally check that `file` is not a directory, as on Windows
1285+ # directories pass the os.access check.
1286+ def _access_check (fn , mode ):
1287+ return (os .path .exists (fn ) and os .access (fn , mode )
1288+ and not os .path .isdir (fn ))
1289+
1290+
12821291def which (cmd , mode = os .F_OK | os .X_OK , path = None ):
12831292 """Given a command, mode, and a PATH string, return the path which
12841293 conforms to the given mode on the PATH, or None if there is no such
@@ -1289,13 +1298,6 @@ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
12891298 path.
12901299
12911300 """
1292- # Check that a given file can be accessed with the correct mode.
1293- # Additionally check that `file` is not a directory, as on Windows
1294- # directories pass the os.access check.
1295- def _access_check (fn , mode ):
1296- return (os .path .exists (fn ) and os .access (fn , mode )
1297- and not os .path .isdir (fn ))
1298-
12991301 # If we're given a path with a directory part, look it up directly rather
13001302 # than referring to PATH directories. This includes checking relative to the
13011303 # current directory, e.g. ./script
@@ -1304,19 +1306,31 @@ def _access_check(fn, mode):
13041306 return cmd
13051307 return None
13061308
1309+ use_bytes = isinstance (cmd , bytes )
1310+
13071311 if path is None :
13081312 path = os .environ .get ("PATH" , os .defpath )
13091313 if not path :
13101314 return None
1311- path = path .split (os .pathsep )
1315+ if use_bytes :
1316+ path = os .fsencode (path )
1317+ path = path .split (os .fsencode (os .pathsep ))
1318+ else :
1319+ path = os .fsdecode (path )
1320+ path = path .split (os .pathsep )
13121321
13131322 if sys .platform == "win32" :
13141323 # The current directory takes precedence on Windows.
1315- if not os .curdir in path :
1316- path .insert (0 , os .curdir )
1324+ curdir = os .curdir
1325+ if use_bytes :
1326+ curdir = os .fsencode (curdir )
1327+ if curdir not in path :
1328+ path .insert (0 , curdir )
13171329
13181330 # PATHEXT is necessary to check on Windows.
13191331 pathext = os .environ .get ("PATHEXT" , "" ).split (os .pathsep )
1332+ if use_bytes :
1333+ pathext = [os .fsencode (ext ) for ext in pathext ]
13201334 # See if the given file matches any of the expected path extensions.
13211335 # This will allow us to short circuit when given "python.exe".
13221336 # If it does match, only test that one, otherwise we have to try
0 commit comments