You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.7 KiB

4 years ago
  1. try:
  2. from shutil import which # Python >= 3.3
  3. except ImportError:
  4. import os, sys
  5. # This is copied from Python 3.4.1
  6. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  7. """Given a command, mode, and a PATH string, return the path which
  8. conforms to the given mode on the PATH, or None if there is no such
  9. file.
  10. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  11. of os.environ.get("PATH"), or can be overridden with a custom search
  12. path.
  13. """
  14. # Check that a given file can be accessed with the correct mode.
  15. # Additionally check that `file` is not a directory, as on Windows
  16. # directories pass the os.access check.
  17. def _access_check(fn, mode):
  18. return (os.path.exists(fn) and os.access(fn, mode)
  19. and not os.path.isdir(fn))
  20. # If we're given a path with a directory part, look it up directly rather
  21. # than referring to PATH directories. This includes checking relative to the
  22. # current directory, e.g. ./script
  23. if os.path.dirname(cmd):
  24. if _access_check(cmd, mode):
  25. return cmd
  26. return None
  27. if path is None:
  28. path = os.environ.get("PATH", os.defpath)
  29. if not path:
  30. return None
  31. path = path.split(os.pathsep)
  32. if sys.platform == "win32":
  33. # The current directory takes precedence on Windows.
  34. if not os.curdir in path:
  35. path.insert(0, os.curdir)
  36. # PATHEXT is necessary to check on Windows.
  37. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  38. # See if the given file matches any of the expected path extensions.
  39. # This will allow us to short circuit when given "python.exe".
  40. # If it does match, only test that one, otherwise we have to try
  41. # others.
  42. if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
  43. files = [cmd]
  44. else:
  45. files = [cmd + ext for ext in pathext]
  46. else:
  47. # On other platforms you don't have things like PATHEXT to tell you
  48. # what file suffixes are executable, so just pass on cmd as-is.
  49. files = [cmd]
  50. seen = set()
  51. for dir in path:
  52. normdir = os.path.normcase(dir)
  53. if not normdir in seen:
  54. seen.add(normdir)
  55. for thefile in files:
  56. name = os.path.join(dir, thefile)
  57. if _access_check(name, mode):
  58. return name
  59. return None
  60. class PtyProcessError(Exception):
  61. """Generic error class for this package."""