diff options
Diffstat (limited to 'python/vyos/util.py')
| -rw-r--r-- | python/vyos/util.py | 51 | 
1 files changed, 51 insertions, 0 deletions
| diff --git a/python/vyos/util.py b/python/vyos/util.py index 8b3de7999..3c454ed4a 100644 --- a/python/vyos/util.py +++ b/python/vyos/util.py @@ -14,7 +14,13 @@  # License along with this library.  If not, see <http://www.gnu.org/licenses/>.  import re +import psutil +def read_file(path): +    """ Read a file to string """ +    with open(path, 'r') as f: +        data = f.read().strip() +    return data  def colon_separated_to_dict(data_string, uniquekeys=False):      """ Converts a string containing newline-separated entries @@ -63,3 +69,48 @@ def colon_separated_to_dict(data_string, uniquekeys=False):              pass      return data + +def process_running(pid_file): +    """ Checks if a process with PID in pid_file is running """ +    with open(pid_file, 'r') as f: +        pid = f.read().strip() +    return psutil.pid_exists(int(pid)) + +def seconds_to_human(s, separator=""): +    """ Converts number of seconds passed to a human-readable +    interval such as 1w4d18h35m59s +    """ +    s = int(s) + +    week = 60 * 60 * 24 * 7 +    day = 60 * 60 * 24 +    hour = 60 * 60 + +    remainder = 0 +    result = "" + +    weeks = s // week +    if weeks > 0: +        result = "{0}w".format(weeks) +        s = s % week + +    days = s // day +    if days > 0: +        result = "{0}{1}{2}d".format(result, separator, days) +        s = s % day + +    hours = s // hour +    if hours > 0: +        result = "{0}{1}{2}h".format(result, separator, hours) +        s = s % hour + +    minutes = s // 60 +    if minutes > 0: +        result = "{0}{1}{2}m".format(result, separator, minutes) +        s = s % 60 + +    seconds = s +    if seconds > 0: +        result = "{0}{1}{2}s".format(result, separator, seconds) + +    return result | 
