Last active
July 2, 2019 17:32
-
-
Save zyxue/6d20ba2bc5efe55b906411ce4649ba88 to your computer and use it in GitHub Desktop.
cheatsheet utils.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import logging | |
from functools import update_wrapper | |
logging.basicConfig( | |
level=logging.DEBUG, format='%(asctime)s|%(levelname)s|%(message)s') | |
def decorator(d): | |
"Make function d a decorator: d wraps a function fn." | |
def _d(fn): | |
return update_wrapper(d(fn), fn) | |
update_wrapper(_d, d) | |
return _d | |
@decorator | |
def timeit(f): | |
"""time a function, used as decorator""" | |
def new_f(*args, **kwargs): | |
bt = time.time() | |
r = f(*args, **kwargs) | |
et = time.time() | |
logging.info(f"time spent on {f.__name__}: {et - bt:.2f}s") | |
return r | |
return new_f | |
def backup_file(f): | |
""" | |
Back up a file, old_file will be renamed to #old_file.n#, where n is a | |
number incremented each time a backup takes place | |
""" | |
if os.path.exists(f): | |
dirname = os.path.dirname(f) | |
basename = os.path.basename(f) | |
count = 1 | |
rn_to = os.path.join( | |
dirname, '#' + basename + '.{0}#'.format(count)) | |
while os.path.exists(rn_to): | |
count += 1 | |
rn_to = os.path.join( | |
dirname, '#' + basename + '.{0}#'.format(count)) | |
logging.info("Backing up {0} to {1}".format(f, rn_to)) | |
os.rename(f, rn_to) | |
return rn_to |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment