You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

94 lines
2.9 KiB

  1. """File-like objects that add timestamps to the input lines"""
  2. from nilmdb.utils.printf import *
  3. import nilmdb.utils.time
  4. class Timestamper(object):
  5. """A file-like object that adds timestamps to lines of an input file."""
  6. def __init__(self, infile, ts_iter):
  7. """file: filename, or another file-like object
  8. ts_iter: iterator that returns a timestamp string for
  9. each line of the file"""
  10. if isinstance(infile, str):
  11. self.file = open(infile, "r")
  12. else:
  13. self.file = infile
  14. self.ts_iter = ts_iter
  15. def close(self):
  16. self.file.close()
  17. def readline(self, *args):
  18. while True:
  19. line = self.file.readline(*args)
  20. if not line:
  21. return ""
  22. if line[0] == '#':
  23. continue
  24. break
  25. try:
  26. return next(self.ts_iter) + line
  27. except StopIteration:
  28. return ""
  29. def readlines(self, size = None):
  30. out = ""
  31. while True:
  32. line = self.readline()
  33. out += line
  34. if not line or (size and len(out) >= size):
  35. break
  36. return out
  37. def __iter__(self):
  38. return self
  39. def __next__(self):
  40. result = self.readline()
  41. if not result:
  42. raise StopIteration
  43. return result
  44. class TimestamperRate(Timestamper):
  45. """Timestamper that uses a start time and a fixed rate"""
  46. def __init__(self, infile, start, rate, end = None):
  47. """
  48. file: file name or object
  49. start: Unix timestamp for the first value
  50. rate: 1/rate is added to the timestamp for each line
  51. end: If specified, raise StopIteration before outputting a value
  52. greater than this."""
  53. timestamp_to_string = nilmdb.utils.time.timestamp_to_string
  54. rate_to_period = nilmdb.utils.time.rate_to_period
  55. def iterator(start, rate, end):
  56. n = 0
  57. rate = float(rate)
  58. while True:
  59. now = start + rate_to_period(rate, n)
  60. if end and now >= end:
  61. raise StopIteration
  62. yield timestamp_to_string(now) + " "
  63. n += 1
  64. Timestamper.__init__(self, infile, iterator(start, rate, end))
  65. self.start = start
  66. self.rate = rate
  67. def __str__(self):
  68. return sprintf("TimestamperRate(..., start=\"%s\", rate=%g)",
  69. nilmdb.utils.time.timestamp_to_human(self.start),
  70. self.rate)
  71. class TimestamperNow(Timestamper):
  72. """Timestamper that uses current time"""
  73. def __init__(self, infile):
  74. timestamp_to_string = nilmdb.utils.time.timestamp_to_string
  75. get_now = nilmdb.utils.time.now
  76. def iterator():
  77. while True:
  78. yield timestamp_to_string(get_now()) + " "
  79. Timestamper.__init__(self, infile, iterator())
  80. def __str__(self):
  81. return "TimestamperNow(...)"