from __future__ import with_statement

import os
import subprocess
import sys


def relpath(base, path):
    """
    Computes the os.sep-joined
    part of a given path relative to the base.

    E.g.

    "/root", "/root/foo/bar" -> "foo/bar"

    """
    parts = []
    while path != base:
        parts.append(path.basename())
        path = path.directory()
    return os.sep.join(reversed(parts))


def assert_(condition, message):
    assert condition(), message


def check_exe_running(exe):
    if sys.platform == "darwin":
        p = subprocess.Popen(["ps", "-x"], stdout=subprocess.PIPE)
        stdout, _ = p.communicate()
        for line in stdout.split("\n"):
            if exe in line:
                return True
        return False
    else:
        try:
            with open(exe, "a"):
                pass
            return False
        except IOError:
            return True
