Roughly the same as os.path.expanduser, but you can pass a default user.

def expand_user(path, user=None):
    """Roughly the same as os.path.expanduser, but you can pass a default user."""

    def _replace(m):
        m_user = m.group(1) or user
        return pwd.getpwnam(m_user).pw_dir if m_user else pwd.getpwuid(os.getuid()).pw_dir

    return re.sub(r'~(\w*)', _replace, path)