common.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. import os, sys, datetime, hashlib
  4. import subprocess, shlex, logging
  5. HOME_PATH = os.path.expanduser("~/autologger")
  6. LOG_PATH = "{}/log".format(HOME_PATH)
  7. TMP_PATH = "{}/tmp".format(HOME_PATH)
  8. BAG_PATH = "{}/bag".format(HOME_PATH)
  9. BAG_PREFIX = "autologger"
  10. def genhash(path):
  11. h = hashlib.md5(open(path, "rb").read())
  12. return h.hexdigest()
  13. def chkhash(hsh, path):
  14. return (hsh == genhash(path))
  15. def normpath(path):
  16. return os.path.normpath(os.path.expanduser(path))
  17. def execmd(cmd, blocking=True):
  18. p = subprocess.Popen(shlex.split(cmd),
  19. stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  20. if blocking: p.wait()
  21. return p
  22. def gendir(path):
  23. if not os.path.exists(path): os.makedirs(path)
  24. def getutime():
  25. return datetime.datetime.now().strftime("%s.%f")
  26. def getdate(ns=False):
  27. fmt = "%Y-%m-%d-%H-%M-%S"
  28. fmt = fmt + "-%f" if ns else fmt # add nsec
  29. return datetime.datetime.now().strftime(fmt)
  30. def genlogger():
  31. # logger settings
  32. name = os.path.basename(sys.argv[0])
  33. logger = logging.getLogger(name)
  34. logger.setLevel(logging.DEBUG)
  35. # formatter
  36. fmt = "%(asctime)s : %(lineno)d : %(levelname)s : %(message)s"
  37. fmtr = logging.Formatter(fmt)
  38. # file handler
  39. gendir(LOG_PATH)
  40. fn = "{}/{}_{}.log".format(LOG_PATH, name, getdate())
  41. fh = logging.FileHandler(fn)
  42. fh.setFormatter(fmtr)
  43. logger.addHandler(fh)
  44. # stream handler
  45. sh = logging.StreamHandler()
  46. logger.addHandler(sh)
  47. sh.setFormatter(fmtr)
  48. return logger