/openerp/tools/which.py

https://gitlab.com/thanhchatvn/cloud-odoo · Python · 153 lines · 113 code · 12 blank · 28 comment · 51 complexity · 1135bd81988a110095d6afaaa5d6f363 MD5 · raw file

  1. #!/usr/bin/env python
  2. """ Which - locate a command
  3. * adapted from Brian Curtin's http://bugs.python.org/file15381/shutil_which.patch
  4. * see http://bugs.python.org/issue444582
  5. * uses ``PATHEXT`` on Windows
  6. * searches current directory before ``PATH`` on Windows,
  7. but not before an explicitly passed path
  8. * accepts both string or iterable for an explicitly passed path, or pathext
  9. * accepts an explicitly passed empty path, or pathext (either '' or [])
  10. * does not search ``PATH`` for files that have a path specified in their name already
  11. * moved defpath and defpathext lists initialization to module level,
  12. instead of initializing them on each function call
  13. * changed interface: which_files() returns generator, which() returns first match,
  14. or raises IOError(errno.ENOENT)
  15. .. function:: which_files(file [, mode=os.F_OK | os.X_OK[, path=None[, pathext=None]]])
  16. Return a generator which yields full paths in which the *file* name exists
  17. in a directory that is part of the file name, or on *path*,
  18. and has the given *mode*.
  19. By default, *mode* matches an inclusive OR of os.F_OK and os.X_OK - an
  20. existing executable file.
  21. The *path* is, by default, the ``PATH`` variable on the platform,
  22. or the string/iterable passed in as *path*.
  23. In the event that a ``PATH`` variable is not found, :const:`os.defpath` is used.
  24. On Windows, a current directory is searched before using the ``PATH`` variable,
  25. but not before an explicitly passed *path*.
  26. The *pathext* is only used on Windows to match files with given extensions appended as well.
  27. It defaults to the ``PATHEXT`` variable, or the string/iterable passed in as *pathext*.
  28. In the event that a ``PATHEXT`` variable is not found,
  29. default value for Windows XP/Vista is used.
  30. The command is always searched without extension first,
  31. even when *pathext* is explicitly passed.
  32. .. function:: which(file [, mode=os.F_OK | os.X_OK[, path=None[, pathext=None]]])
  33. Return first match generated by which_files(file, mode, path, pathext),
  34. or raise IOError(errno.ENOENT).
  35. """
  36. __docformat__ = 'restructuredtext en'
  37. __all__ = 'which which_files pathsep defpath defpathext F_OK R_OK W_OK X_OK'.split()
  38. import sys
  39. from os import access, defpath, pathsep, environ, F_OK, R_OK, W_OK, X_OK
  40. from os.path import exists, dirname, split, join
  41. windows = sys.platform.startswith('win')
  42. defpath = environ.get('PATH', defpath).split(pathsep)
  43. if windows:
  44. defpath.insert(0, '.') # can insert without checking, when duplicates are removed
  45. # given the quite usual mess in PATH on Windows, let's rather remove duplicates
  46. seen = set()
  47. defpath = [dir for dir in defpath if dir.lower() not in seen and not seen.add(dir.lower())]
  48. del seen
  49. defpathext = [''] + environ.get('PATHEXT',
  50. '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC').lower().split(pathsep)
  51. else:
  52. defpathext = ['']
  53. def which_files(file, mode=F_OK | X_OK, path=None, pathext=None):
  54. """ Locate a file in a path supplied as a part of the file name,
  55. or the user's path, or a supplied path.
  56. The function yields full paths (not necessarily absolute paths),
  57. in which the given file name matches an existing file in a directory on the path.
  58. >>> def test_which(expected, *args, **argd):
  59. ... result = list(which_files(*args, **argd))
  60. ... assert result == expected, 'which_files: %s != %s' % (result, expected)
  61. ...
  62. ... try:
  63. ... result = [ which(*args, **argd) ]
  64. ... except IOError:
  65. ... result = []
  66. ... assert result[:1] == expected[:1], 'which: %s != %s' % (result[:1], expected[:1])
  67. >>> if windows: cmd = environ['COMSPEC']
  68. >>> if windows: test_which([cmd], 'cmd')
  69. >>> if windows: test_which([cmd], 'cmd.exe')
  70. >>> if windows: test_which([cmd], 'cmd', path=dirname(cmd))
  71. >>> if windows: test_which([cmd], 'cmd', pathext='.exe')
  72. >>> if windows: test_which([cmd], cmd)
  73. >>> if windows: test_which([cmd], cmd, path='<nonexistent>')
  74. >>> if windows: test_which([cmd], cmd, pathext='<nonexistent>')
  75. >>> if windows: test_which([cmd], cmd[:-4])
  76. >>> if windows: test_which([cmd], cmd[:-4], path='<nonexistent>')
  77. >>> if windows: test_which([], 'cmd', path='<nonexistent>')
  78. >>> if windows: test_which([], 'cmd', pathext='<nonexistent>')
  79. >>> if windows: test_which([], '<nonexistent>/cmd')
  80. >>> if windows: test_which([], cmd[:-4], pathext='<nonexistent>')
  81. >>> if not windows: sh = '/bin/sh'
  82. >>> if not windows: test_which([sh], 'sh')
  83. >>> if not windows: test_which([sh], 'sh', path=dirname(sh))
  84. >>> if not windows: test_which([sh], 'sh', pathext='<nonexistent>')
  85. >>> if not windows: test_which([sh], sh)
  86. >>> if not windows: test_which([sh], sh, path='<nonexistent>')
  87. >>> if not windows: test_which([sh], sh, pathext='<nonexistent>')
  88. >>> if not windows: test_which([], 'sh', mode=W_OK) # not running as root, are you?
  89. >>> if not windows: test_which([], 'sh', path='<nonexistent>')
  90. >>> if not windows: test_which([], '<nonexistent>/sh')
  91. """
  92. filepath, file = split(file)
  93. if filepath:
  94. path = (filepath,)
  95. elif path is None:
  96. path = defpath
  97. elif isinstance(path, str):
  98. path = path.split(pathsep)
  99. if pathext is None:
  100. pathext = defpathext
  101. elif isinstance(pathext, str):
  102. pathext = pathext.split(pathsep)
  103. if not '' in pathext:
  104. pathext.insert(0, '') # always check command without extension, even for custom pathext
  105. for dir in path:
  106. basepath = join(dir, file)
  107. for ext in pathext:
  108. fullpath = basepath + ext
  109. if exists(fullpath) and access(fullpath, mode):
  110. yield fullpath
  111. def which(file, mode=F_OK | X_OK, path=None, pathext=None):
  112. """ Locate a file in a path supplied as a part of the file name,
  113. or the user's path, or a supplied path.
  114. The function returns full path (not necessarily absolute path),
  115. in which the given file name matches an existing file in a directory on the path,
  116. or raises IOError(errno.ENOENT).
  117. >>> # for doctest see which_files()
  118. """
  119. try:
  120. return iter(which_files(file, mode, path, pathext)).next()
  121. except StopIteration:
  122. try:
  123. from errno import ENOENT
  124. except ImportError:
  125. ENOENT = 2
  126. raise IOError(ENOENT, '%s not found' % (mode & X_OK and 'command' or 'file'), file)
  127. if __name__ == '__main__':
  128. import doctest
  129. doctest.testmod()