summaryrefslogtreecommitdiff
path: root/obalie/utils.py
blob: 2d4be0e777be73d8258e42d119201bb98c109a4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# vim: set filencoding=utf8
"""
Miscellaneous Utility Commands

@author: Mike Crute (mcrute@ag.com)
@organization: SoftGroup Interactive, Inc.
@date: April 20, 2010
"""


import shlex
from urlparse import urljoin
from subprocess import Popen, PIPE
from obalie.exceptions import ExecutableError


def run_command(command, raw_output=False):
    """
    Run a command string returning the output. Passing raw_output
    will cause the function to return the raw stdout; otherwise
    lines will be split.
    """
    cmd = shlex.split(command.encode('ascii'))
    proc = Popen(cmd, close_fds=False, stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()

    if proc.returncode != 0:
        raise ExecutableError(proc.returncode, command)

    if raw_output:
        return stdout
    else:
        return stdout.splitlines(True)


def join_url(base, path):
    """
    Joins a URL but ignores the leading slash on the path that would
    otherwise truncate the base part back to the hostname.
    """
    path = path.lstrip('/')
    return urljoin(base, path)