Source code for utils

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <>
# Author: Francois Boulogne <fboulogne at sciunto dot org>, 2012

import tarfile
import os.path
import os
import logging
import datetime

logger = logging.getLogger('Vitalus.utils')

[docs]def r_chmod(path, mode): """ Equivalent to chmod -R mod path :param path: path :param mode: mode """ os.chmod(path, mode) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isfile(itempath): os.chmod(itempath, mode) elif os.path.isdir(itempath): os.chmod(itempath, mode) r_chmod(itempath, mode)
[docs]def r_chown(path, uid, gid): """ Equivalent to chown -R uid:gid path :param path: path :param uid: user ID :param gid: group ID """ os.chown(path, uid, gid) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isfile(itempath): os.chown(itempath, uid, gid) elif os.path.isdir(itempath): os.chown(itempath, uid, gid) r_chown(itempath, uid, gid)
[docs]def compress(path): """ Compress the directory """ head, tail = os.path.split(path) archive = str(path) + '.bz2' tar =, "w:bz2") tar.add(path, arcname=tail) tar.close()
[docs]def get_folder_size(path): """ Get the size of the content in path """ size = 0 for item in os.walk(path): for file in item[2]: try: size += os.path.getsize(os.path.join(item[0], file)) except: logger.error("Impossible to get size of: %s", os.path.join(item[0], file)) return size
[docs]def get_last_file(file_list): """ Return the more recent file in a list (in the format "%Y-%m-%d_%Hh%Mm%Ss") :param file_list: list of files :return: filename """ if file_list == []: return None last_date = datetime.datetime(1, 1, 1, 0, 0) last = None for afile in file_list: try: date = datetime.datetime.strptime(afile, '%Y-%m-%d_%Hh%Mm%Ss') except ValueError: continue if date > last_date: last_date = date last = afile return last
[docs]def get_older_files(file_list, days=5, keep=10): """ Deprecated. Use Vitalus.history.older_keepmin() """ from Vitalus import history return history.older_keepmin(file_list, days=days, keep=keep)