PageRenderTime 57ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/components/tools/OmeroPy/src/omero_ext/which.py

https://github.com/aherbert/openmicroscopy
Python | 335 lines | 309 code | 2 blank | 24 comment | 4 complexity | b327becbcc8e70d0dea2345eaeeb02dc MD5 | raw file
  1. #!/usr/bin/env python
  2. # Copyright (c) 2002-2005 ActiveState Corp.
  3. # See LICENSE.txt for license details.
  4. # Author:
  5. # Trent Mick (TrentM@ActiveState.com)
  6. # Home:
  7. # http://trentm.com/projects/which/
  8. r"""Find the full path to commands.
  9. which(command, path=None, verbose=0, exts=None)
  10. Return the full path to the first match of the given command on the
  11. path.
  12. whichall(command, path=None, verbose=0, exts=None)
  13. Return a list of full paths to all matches of the given command on
  14. the path.
  15. whichgen(command, path=None, verbose=0, exts=None)
  16. Return a generator which will yield full paths to all matches of the
  17. given command on the path.
  18. By default the PATH environment variable is searched (as well as, on
  19. Windows, the AppPaths key in the registry), but a specific 'path' list
  20. to search may be specified as well. On Windows, the PATHEXT environment
  21. variable is applied as appropriate.
  22. If "verbose" is true then a tuple of the form
  23. (<fullpath>, <matched-where-description>)
  24. is returned for each match. The latter element is a textual description
  25. of where the match was found. For example:
  26. from PATH element 0
  27. from HKLM\SOFTWARE\...\perl.exe
  28. """
  29. _cmdlnUsage = """
  30. Show the full path of commands.
  31. Usage:
  32. which [<options>...] [<command-name>...]
  33. Options:
  34. -h, --help Print this help and exit.
  35. -V, --version Print the version info and exit.
  36. -a, --all Print *all* matching paths.
  37. -v, --verbose Print out how matches were located and
  38. show near misses on stderr.
  39. -q, --quiet Just print out matches. I.e., do not print out
  40. near misses.
  41. -p <altpath>, --path=<altpath>
  42. An alternative path (list of directories) may
  43. be specified for searching.
  44. -e <exts>, --exts=<exts>
  45. Specify a list of extensions to consider instead
  46. of the usual list (';'-separate list, Windows
  47. only).
  48. Show the full path to the program that would be run for each given
  49. command name, if any. Which, like GNU's which, returns the number of
  50. failed arguments, or -1 when no <command-name> was given.
  51. Near misses include duplicates, non-regular files and (on Un*x)
  52. files without executable access.
  53. """
  54. __revision__ = "$Id: which.py 430 2005-08-20 03:11:58Z trentm $"
  55. __version_info__ = (1, 1, 0)
  56. __version__ = '.'.join(map(str, __version_info__))
  57. import os
  58. import sys
  59. import getopt
  60. import stat
  61. #---- exceptions
  62. class WhichError(Exception):
  63. pass
  64. #---- internal support stuff
  65. def _getRegisteredExecutable(exeName):
  66. """Windows allow application paths to be registered in the registry."""
  67. registered = None
  68. if sys.platform.startswith('win'):
  69. if os.path.splitext(exeName)[1].lower() != '.exe':
  70. exeName += '.exe'
  71. import _winreg
  72. try:
  73. key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\
  74. exeName
  75. value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)
  76. registered = (value, "from HKLM\\"+key)
  77. except _winreg.error:
  78. pass
  79. if registered and not os.path.exists(registered[0]):
  80. registered = None
  81. return registered
  82. def _samefile(fname1, fname2):
  83. if sys.platform.startswith('win'):
  84. return ( os.path.normpath(os.path.normcase(fname1)) ==\
  85. os.path.normpath(os.path.normcase(fname2)) )
  86. else:
  87. return os.path.samefile(fname1, fname2)
  88. def _cull(potential, matches, verbose=0):
  89. """Cull inappropriate matches. Possible reasons:
  90. - a duplicate of a previous match
  91. - not a disk file
  92. - not executable (non-Windows)
  93. If 'potential' is approved it is returned and added to 'matches'.
  94. Otherwise, None is returned.
  95. """
  96. for match in matches: # don't yield duplicates
  97. if _samefile(potential[0], match[0]):
  98. if verbose:
  99. sys.stderr.write("duplicate: %s (%s)\n" % potential)
  100. return None
  101. else:
  102. if not stat.S_ISREG(os.stat(potential[0]).st_mode):
  103. if verbose:
  104. sys.stderr.write("not a regular file: %s (%s)\n" % potential)
  105. elif not os.access(potential[0], os.X_OK):
  106. if verbose:
  107. sys.stderr.write("no executable access: %s (%s)\n"\
  108. % potential)
  109. else:
  110. matches.append(potential)
  111. return potential
  112. #---- module API
  113. def whichgen(command, path=None, verbose=0, exts=None):
  114. """Return a generator of full paths to the given command.
  115. "command" is a the name of the executable to search for.
  116. "path" is an optional alternate path list to search. The default it
  117. to use the PATH environment variable.
  118. "verbose", if true, will cause a 2-tuple to be returned for each
  119. match. The second element is a textual description of where the
  120. match was found.
  121. "exts" optionally allows one to specify a list of extensions to use
  122. instead of the standard list for this system. This can
  123. effectively be used as an optimization to, for example, avoid
  124. stat's of "foo.vbs" when searching for "foo" and you know it is
  125. not a VisualBasic script but ".vbs" is on PATHEXT. This option
  126. is only supported on Windows.
  127. This method returns a generator which yields either full paths to
  128. the given command or, if verbose, tuples of the form (<path to
  129. command>, <where path found>).
  130. """
  131. matches = []
  132. if path is None:
  133. usingGivenPath = 0
  134. path = os.environ.get("PATH", "").split(os.pathsep)
  135. if sys.platform.startswith("win"):
  136. path.insert(0, os.curdir) # implied by Windows shell
  137. else:
  138. usingGivenPath = 1
  139. # Windows has the concept of a list of extensions (PATHEXT env var).
  140. if sys.platform.startswith("win"):
  141. if exts is None:
  142. exts = os.environ.get("PATHEXT", "").split(os.pathsep)
  143. # If '.exe' is not in exts then obviously this is Win9x and
  144. # or a bogus PATHEXT, then use a reasonable default.
  145. for ext in exts:
  146. if ext.lower() == ".exe":
  147. break
  148. else:
  149. exts = ['.COM', '.EXE', '.BAT']
  150. elif not isinstance(exts, list):
  151. raise TypeError("'exts' argument must be a list or None")
  152. else:
  153. if exts is not None:
  154. raise WhichError("'exts' argument is not supported on "\
  155. "platform '%s'" % sys.platform)
  156. exts = []
  157. # File name cannot have path separators because PATH lookup does not
  158. # work that way.
  159. if os.sep in command or os.altsep and os.altsep in command:
  160. pass
  161. else:
  162. for i in range(len(path)):
  163. dirName = path[i]
  164. # On windows the dirName *could* be quoted, drop the quotes
  165. if sys.platform.startswith("win") and len(dirName) >= 2\
  166. and dirName[0] == '"' and dirName[-1] == '"':
  167. dirName = dirName[1:-1]
  168. for ext in ['']+exts:
  169. absName = os.path.abspath(
  170. os.path.normpath(os.path.join(dirName, command+ext)))
  171. if os.path.isfile(absName):
  172. if usingGivenPath:
  173. fromWhere = "from given path element %d" % i
  174. elif not sys.platform.startswith("win"):
  175. fromWhere = "from PATH element %d" % i
  176. elif i == 0:
  177. fromWhere = "from current directory"
  178. else:
  179. fromWhere = "from PATH element %d" % (i-1)
  180. match = _cull((absName, fromWhere), matches, verbose)
  181. if match:
  182. if verbose:
  183. yield match
  184. else:
  185. yield match[0]
  186. match = _getRegisteredExecutable(command)
  187. if match is not None:
  188. match = _cull(match, matches, verbose)
  189. if match:
  190. if verbose:
  191. yield match
  192. else:
  193. yield match[0]
  194. def which(command, path=None, verbose=0, exts=None):
  195. """Return the full path to the first match of the given command on
  196. the path.
  197. "command" is a the name of the executable to search for.
  198. "path" is an optional alternate path list to search. The default it
  199. to use the PATH environment variable.
  200. "verbose", if true, will cause a 2-tuple to be returned. The second
  201. element is a textual description of where the match was found.
  202. "exts" optionally allows one to specify a list of extensions to use
  203. instead of the standard list for this system. This can
  204. effectively be used as an optimization to, for example, avoid
  205. stat's of "foo.vbs" when searching for "foo" and you know it is
  206. not a VisualBasic script but ".vbs" is on PATHEXT. This option
  207. is only supported on Windows.
  208. If no match is found for the command, a WhichError is raised.
  209. """
  210. try:
  211. match = whichgen(command, path, verbose, exts).next()
  212. except StopIteration:
  213. raise WhichError("Could not find '%s' on the path." % command)
  214. return match
  215. def whichall(command, path=None, verbose=0, exts=None):
  216. """Return a list of full paths to all matches of the given command
  217. on the path.
  218. "command" is a the name of the executable to search for.
  219. "path" is an optional alternate path list to search. The default it
  220. to use the PATH environment variable.
  221. "verbose", if true, will cause a 2-tuple to be returned for each
  222. match. The second element is a textual description of where the
  223. match was found.
  224. "exts" optionally allows one to specify a list of extensions to use
  225. instead of the standard list for this system. This can
  226. effectively be used as an optimization to, for example, avoid
  227. stat's of "foo.vbs" when searching for "foo" and you know it is
  228. not a VisualBasic script but ".vbs" is on PATHEXT. This option
  229. is only supported on Windows.
  230. """
  231. return list( whichgen(command, path, verbose, exts) )
  232. #---- mainline
  233. def main(argv):
  234. all = 0
  235. verbose = 0
  236. altpath = None
  237. exts = None
  238. try:
  239. optlist, args = getopt.getopt(argv[1:], 'haVvqp:e:',
  240. ['help', 'all', 'version', 'verbose', 'quiet', 'path=', 'exts='])
  241. except getopt.GetoptError, msg:
  242. sys.stderr.write("which: error: %s. Your invocation was: %s\n"\
  243. % (msg, argv))
  244. sys.stderr.write("Try 'which --help'.\n")
  245. return 1
  246. for opt, optarg in optlist:
  247. if opt in ('-h', '--help'):
  248. print _cmdlnUsage
  249. return 0
  250. elif opt in ('-V', '--version'):
  251. print "which %s" % __version__
  252. return 0
  253. elif opt in ('-a', '--all'):
  254. all = 1
  255. elif opt in ('-v', '--verbose'):
  256. verbose = 1
  257. elif opt in ('-q', '--quiet'):
  258. verbose = 0
  259. elif opt in ('-p', '--path'):
  260. if optarg:
  261. altpath = optarg.split(os.pathsep)
  262. else:
  263. altpath = []
  264. elif opt in ('-e', '--exts'):
  265. if optarg:
  266. exts = optarg.split(os.pathsep)
  267. else:
  268. exts = []
  269. if len(args) == 0:
  270. return -1
  271. failures = 0
  272. for arg in args:
  273. #print "debug: search for %r" % arg
  274. nmatches = 0
  275. for match in whichgen(arg, path=altpath, verbose=verbose, exts=exts):
  276. if verbose:
  277. print "%s (%s)" % match
  278. else:
  279. print match
  280. nmatches += 1
  281. if not all:
  282. break
  283. if not nmatches:
  284. failures += 1
  285. return failures
  286. if __name__ == "__main__":
  287. sys.exit( main(sys.argv) )