How to use the sarge.Capture function in sarge

To help you get started, we’ve selected a few sarge examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mozilla-services / screenshots / test / server / test_file_management.py View on Github external
for key in extra_env:
        extra_env[key] = str(extra_env[key])
    if server and server_options == extra_env:
        print("  Server already started with correct options")
        return
    stop_server()
    env = os.environ.copy()
    env.update(extra_env)
    env['PORT'] = '10180'
    env['SITE_ORIGIN'] = 'localhost:10180'
    env['CONTENT_ORIGIN'] = 'localhost:10180'
    env['GA_ID'] = ''
    env['NODE_ENV'] = 'production'
    env['LOG_QUERY_LIMIT'] = '0'
    env['ENABLE_WATCHDOG'] = 'false'
    server_out = Capture()
    env_print = ['%s=%s' % (name, value) for name, value in sorted(extra_env.items())]
    if env_print:
        env_print = ' (%s)' % ' '.join(env_print)
    else:
        env_print = ''
    print('  Starting server%s' % env_print)
    server = run('./bin/run-server --no-auto', cwd=project_base, env=env, stdout=server_out, async_=True)
    server_options = extra_env
    time.sleep(3)
    text = []
    while True:
        if server.commands[0].process and server.commands[0].poll():
            print('    Server exited with code %s' % server.commands[0].poll())
            text.extend(server_out.readlines())
            for line in text:
                print('      %s' % line.rstrip())
github OctoPrint / OctoPrint-FirmwareUpdater / octoprint_firmwareupdater / methods / stm32flash.py View on Github external
if (stm32flash_reset and not stm32flash_execute):
        stm32flash_args.append('-R')

    stm32flash_args.append('-w')
    stm32flash_args.append(firmware)
    stm32flash_args.append(printer_port)

    stm32flash_command = ' '.join(stm32flash_args)

    self._logger.info(u"Running '{}' in {}".format(stm32flash_command, working_dir))
    self._console_logger.info(u"")
    self._console_logger.info(stm32flash_command)

    try:
        p = sarge.run(stm32flash_command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
        p.wait_events()

        while p.returncode is None:
            output = p.stdout.read(timeout=0.5)
            if not output:
                p.commands[0].poll()
                continue

            for line in output.split("\n"):
                if line.endswith("\r"):
                    line = line[:-1]
                self._console_logger.info(u"> {}".format(line))

                if "Write to memory" in line:
                    self._logger.info(u"Writing memory...")
                    self._send_status("progress", subtype="writing")
github teamplify / teamplify-runner / teamplify_runner / utils.py View on Github external
def run(cmd, raise_on_error=True, capture_output=True, suppress_output=False,
        **kwargs):
    """
    Wrapper around sarge.run that can raise errors and capture stdout.
    """
    if capture_output:
        kwargs['stdout'] = sarge.Capture()
        kwargs['stderr'] = sarge.Capture()
    result = sarge.run(cmd, **kwargs)
    code = result.returncode
    if code and raise_on_error:
        raise RuntimeError('Command failed, exit code %s' % code)
    if capture_output:
        stdout = result.stdout.read()
        result.stdout_lines = stdout.decode().split('\n')
        if result.stdout_lines[-1] == '':
            result.stdout_lines = result.stdout_lines[:-1]
        if not suppress_output:
            if stdout:
                click.echo(stdout)
            stderr = result.stderr.read()
            if stderr:
                click.echo(stderr, err=True)
github ThiefMaster / fsnotifier-remote / fsnotifier.py View on Github external
exe_dir = os.path.dirname(os.path.realpath(sys.executable if hasattr(sys, 'frozen') else sys.argv[0]))
    config_file = os.path.join(exe_dir, 'fsnotifier.yaml')

    try:
        with open(config_file) as f:
            config = yaml.load(f)
    except FileNotFoundError:
        print('Config file not found: {}'.format(config_file))
        sys.exit(1)

    logfile = open(config['log']['file'] if config['log']['enabled'] else os.devnull, 'w')
    config['reverse_mapping'] = {v: '{}:'.format(k) for k, v in config['mapping'].items()}

    # Local notifier
    local_stdin = sarge.Feeder()
    local_watcher = sarge.run(config['fsnotifier']['local'], stdout=sarge.Capture(), input=local_stdin, async_=True)
    local_monitor = LocalMonitorThread(daemon=True)

    # Remote notifier
    ssh_conn = paramiko.SSHClient()
    ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_conn.connect(config['ssh']['host'], username=config['ssh']['user'], allow_agent=True)
    ssh_stdin, ssh_stdout, _ = ssh_conn.exec_command(config['fsnotifier']['remote'])
    remote_monitor = RemoteMonitorThread(daemon=True)

    local_monitor.start()
    remote_monitor.start()

    receiving_roots = False
    new_roots = []
    while True:
        line = sys.stdin.readline()
github orf / xcat / example_application / src / app.py View on Github external
def run_xpath_query(query):
    """
    This executes an xpath query against library.xml. It's horrible and relies on calling an external .jar file,
    which makes it very expensive (0.4s per query). Oh well.
    """

    library_arg = "-s:{library} ".format(library=library)
    args = ["java", "-Xms30m", "-cp", str(saxon_jar), "net.sf.saxon.Query", library_arg, "-", "-wrap", "-ext:off"]

    start = time.time()
    p = run(args, stdout=Capture(), stderr=Capture(), cwd=os.getcwd(), input=query)
    output = p.stdout.read()
    error = p.stderr.read()

    try:
        tree = etree.fromstring(output)
        returner = [
            parse_item(result) for result in tree.getchildren()
            ]
    except Exception:
        returner = []

    end = time.time()
    print("[{time:1.4f}] {cmd}".format(time=end - start, cmd=query))

    return returner, end - start, error
github cosminbasca / cleanmymac / cleanmymac / target.py View on Github external
def _run(self, commands):
        for cmd in commands:
            self._debug('run command "{0}"'.format(cmd))
            try:
                with Capture() as err:
                    with Capture() as out:
                        if self._verbose:
                            echo_success('running: {0}'.format(cmd))

                        command_done = Event()

                        def redirect():
                            while not command_done.is_set():
                                try:
                                    for line in out:
                                        echo_info(line.strip())
                                except TypeError:
                                    pass

                                try:
                                    for line in err:
github goodplay / goodplay / goodplay / utils / subprocess.py View on Github external
from __future__ import (absolute_import, division, print_function)

import logging
import sarge

log = logging.getLogger(__name__)


def run(command, *args, **kwargs):
    command = sarge.shell_format(command, *args)
    log.info('run process: %s', command)

    return sarge.run(command, stdout=Capture(), stderr=Capture(), **kwargs)


class Capture(sarge.Capture):
    def __iter__(self):
        # override default Capture to read lines as long as streams are open,
        # thus iteration is not being stopped by large pauses between lines
        # being available
        while self.streams_open():
            line = self.readline()
            if not line:
                continue
            yield line.decode('utf-8')

        # ensure remaining buffered lines are consumed (original code)
        while True:
            line = self.readline()
            if not line:
                break
            yield line.decode('utf-8')
github cosminbasca / cleanmymac / cleanmymac / target.py View on Github external
def _run(self, commands):
        for cmd in commands:
            self._debug('run command "{0}"'.format(cmd))
            try:
                with Capture() as err:
                    with Capture() as out:
                        if self._verbose:
                            echo_success('running: {0}'.format(cmd))

                        command_done = Event()

                        def redirect():
                            while not command_done.is_set():
                                try:
                                    for line in out:
                                        echo_info(line.strip())
                                except TypeError:
                                    pass

                                try:
                                    for line in err:
                                        warn(line.strip())

sarge

A wrapper for subprocess which provides command pipeline functionality.

BSD-2-Clause
Latest version published 2 years ago

Package Health Score

49 / 100
Full package analysis