import os
import pickle
from collections import defaultdict
import datetime
# load old dict
if os.path.exists('usage_stastic/monthly_stastic/old.dict'):
with open('usage_stastic/monthly_stastic/old.dict', 'rb') as f:
old_dict = pickle.load(f)
else:
old_dict = defaultdict(float)
# get usage data till this month
curr_dict = defaultdict(float)
results = os.popen('ac -p').read().splitlines()
for line in results:
if not line.startswith('\ttotal '):
user_name = line.split(' ')[0].split('\t')[1]
use_time = float(line.split(' ')[-1])
curr_dict[user_name] += use_time
i = datetime.datetime.now()
# save usage data till now
with open('usage_stastic/monthly_stastic/%s-%s-%s_log.dict' % (i.year, i.month, i.day), 'wb') as f:
pickle.dump(curr_dict, f)
# rewrite old dict
with open('usage_stastic/monthly_stastic/old.dict', 'wb') as f:
pickle.dump(curr_dict, f)
# get usage of this month
export_lines = []
delta_dict = defaultdict(float)
for k, v in curr_dict.items():
delta_dict[k] = v - old_dict[k]
export_lines.append("%s,%s\n" % (k, v - old_dict[k]))
# save usage of this month
with open('usage_stastic/monthly_reports/monthly report %s-%s-%s.csv' % (i.year, i.month, i.day), 'w+') as f:
f.write('Username,Usetime(hour)\n')
[f.write(line) for line in export_lines]