snippets.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from shutil import rmtree
  4. def remove(path):
  5. if os.path.exists(path):
  6. if os.path.isdir(path):
  7. rmtree(path)
  8. else:
  9. os.remove(path)
  10. # find all indices of a list of strings that match a regex
  11. def findall_regex(items, regex):
  12. found = list()
  13. for i in range(0, len(items)):
  14. k = regex.match(items[i])
  15. if k:
  16. found.append(i)
  17. k = None
  18. return found
  19. def split_by_regex(items, regex):
  20. splits = list()
  21. indices = findall_regex(items, regex)
  22. if not indices:
  23. splits.append(items)
  24. return splits
  25. # Add first chunk before first match
  26. splits.append(items[0 : indices[0]])
  27. # Add chunks between matches
  28. for i in range(len(indices) - 1):
  29. splits.append(items[indices[i] : indices[i + 1]])
  30. # Add final chunk after last match
  31. splits.append(items[indices[-1] :])
  32. return splits
  33. # http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
  34. def which(program):
  35. def is_exe(fpath):
  36. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  37. fpath, fname = os.path.split(program)
  38. if fpath:
  39. if is_exe(program):
  40. return program
  41. else:
  42. for path in os.environ['PATH'].split(os.pathsep):
  43. path = path.strip('"')
  44. exe_file = os.path.join(path, program)
  45. if is_exe(exe_file):
  46. return exe_file
  47. return None