procutils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Utilities for dealing with processes.
  5. """
  6. from __future__ import division, absolute_import
  7. import os
  8. def which(name, flags=os.X_OK):
  9. """
  10. Search PATH for executable files with the given name.
  11. On newer versions of MS-Windows, the PATHEXT environment variable will be
  12. set to the list of file extensions for files considered executable. This
  13. will normally include things like ".EXE". This function will also find files
  14. with the given name ending with any of these extensions.
  15. On MS-Windows the only flag that has any meaning is os.F_OK. Any other
  16. flags will be ignored.
  17. @type name: C{str}
  18. @param name: The name for which to search.
  19. @type flags: C{int}
  20. @param flags: Arguments to L{os.access}.
  21. @rtype: C{list}
  22. @param: A list of the full paths to files found, in the order in which they
  23. were found.
  24. """
  25. result = []
  26. exts = list(filter(None, os.environ.get('PATHEXT', '').split(os.pathsep)))
  27. path = os.environ.get('PATH', None)
  28. if path is None:
  29. return []
  30. for p in os.environ.get('PATH', '').split(os.pathsep):
  31. p = os.path.join(p, name)
  32. if os.access(p, flags):
  33. result.append(p)
  34. for e in exts:
  35. pext = p + e
  36. if os.access(pext, flags):
  37. result.append(pext)
  38. return result