Exemplo n.º 1
0
def get_run(command: str, directory: str = None) -> str:
    """Run a command and return its standard output as a string.

    Note that anything written to the standard error device will still be written
    to the standard error device.

    Args:
       command: the command, complete with arguments, to be run
       directory: if specified, the command will be run in that directory. If not
                  specified, the command will be run in the current directory.

    Raises:
       ValueError: if the command is empty
       FileNotFoundError: if a non-existant directory is specified
       subprocess.CalledProcessError: if there is a problem running the command.

    If the directory is not specified, then it will run in the current directory.
    """
    contract.parameters(lambda: bool(command))
    logging.debug("Running command: %s", command)
    res = subprocess.run("%s" % command,
                         shell=True,
                         check=True,
                         cwd=directory,
                         stdout=subprocess.PIPE)
    return res.stdout.decode('utf-8').strip()
def from_file(filename: str):
    """Read a JSON from a file.

    Returns:
        Either returns a List or a Dict depending on the file contents.

    Raises:
        ValueError: if the file name is empty
        FileNotFoundError: if the file cannot be read
        json.decoder.JSONDecodeError: if the file contents cannot be interpreted as JSON
    """
    contract.parameters(lambda: bool(filename))
    logging.debug("Reading '%s' as JSON", filename)
    with open(filename) as infile:
        return json.load(infile)
    def test_parameters(self):
        # The only "assertion" for the next lines is that no exception is thrown.
        contract.parameters(lambda: True)
        contract.parameters(lambda: 1 == 1, lambda: "hello" == "hello",
                            lambda: 23 < 32)

        with self.assertRaises(ValueError):
            contract.parameters(lambda: False)

        with self.assertRaises(ValueError):
            contract.parameters(lambda: 1 == 1, lambda: "hello" == "hello23",
                                lambda: 23 < 32)
Exemplo n.º 4
0
def run(command: str, directory: str = None):
    """Run a command.

    Note that anything written to the standard output or error devices, will be
    echoed to that device.

    Args:
       command: the command, complete with arguments, to be run
       directory: if specified, the command will be run in that directory. If not
                  specified, the command will be run in the current directory.

    Raises:
       ValueError: if the command is empty
       FileNotFoundError: if a non-existant directory is specified
       subprocess.CalledProcessError: if there is a problem running the command.

    If the directory is not specified, then it will run in the current directory.
    """
    contract.parameters(lambda: bool(command))
    logging.debug("Running command: %s", command)
    subprocess.run("%s" % command, shell=True, check=True, cwd=directory)
Exemplo n.º 5
0
def process(command: str, directory: str = None, as_string: bool = True):
    """Run a command and return the standard output as a pipe for processing.

    Note that anything written to the standard error device will still be written
    to the standard error device. At present our API does not allow you to determine
    if the command returned an error result or not. If you need to do that, you
    will need to call subprocess.Popen manually.

    Args:
       command: the command, complete with arguments, to be run
       directory: if specified, the command will be run in that directory. If not
                  specified, the command will be run in the current directory.
       as_string: if true, each line will be decoded as a utf-8 string. Otherwise
                  each line will be passed as binary data.

    Raises:
       ValueError: if the command is empty
       FileNotFoundError: if a non-existant directory is specified
       subprocess.CalledProcessError: if there is a problem running the command

    Example:
        for line in command.process('ls -l'):
            print("found: %s" % command.decode(line))

    If the directory is not specified, then it will run in the current directory.
    """
    contract.parameters(lambda: bool(command))
    logging.debug("Processing command: %s", command)
    with subprocess.Popen("%s" % command,
                          shell=True,
                          cwd=directory,
                          stdout=subprocess.PIPE) as pipe:
        for line in pipe.stdout:
            if as_string:
                yield line.decode('utf-8').rstrip()
            else:
                yield line
        pipe.communicate()
        if pipe.returncode != 0:
            raise subprocess.CalledProcessError(pipe.returncode, command)
def from_url(url: str):
    """Read a JSON from a URL.

    Returns:
        Either returns a List or a Dict depending on the returned contents.

    Raises:
        ValueError: if the url is empty
        requests.exceptions.ConnectionError: if the url connection cannot be made
        kss.util.jsonreader.NotOkResponseError: if the url returns a non-OK response
        kss.util.jsonreader.ContentTypeResponseError: if the url does not claim to return
                                                      'application/json'
        json.decoder.JSONDecodeError: if the returned contents cannot be interpreted as JSON
    """
    contract.parameters(lambda: bool(url))
    logging.debug("GET '%s' as JSON", url)
    resp = requests.get(url, headers={'Accept': 'application/json'})
    if not (resp.status_code >= 200 and resp.status_code < 300):
        raise NotOkResponseError(resp.status_code)
    ctype = resp.headers.get('content-type', '')
    if not ctype.startswith('application/json'):
        raise ContentTypeResponseError(ctype)
    return resp.json()