Run an ffmpeg command, trying to capture the process output and calculate
        the duration / progress.
        Yields the progress in percent.
165793
def run_ffmpeg_command(self):
        
        logger.debug("Running ffmpeg command: {}".format(self.cmd))

        if self.dry:
            logger.debug("Dry mode specified, not actually running command")
            return

        total_dur = None

        stderr = []

        p = subprocess.Popen(
            self.cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=False
        )

        # for stderr_line in iter(p.stderr):
        while True:
            line = p.stderr.readline().decode("utf8", errors='replace')
            if line == '' and p.poll() is not None:
                break
            stderr.append(line.strip())
            self.output = "\n".join(stderr)

            if not total_dur and CommandRunner.DUR_REGEX.search(line):
                total_dur = CommandRunner.DUR_REGEX.search(line).groupdict()
                total_dur = to_ms(**total_dur)
                continue
            if total_dur:
                result = CommandRunner.TIME_REGEX.search(line)
                if result:
                    elapsed_time = to_ms(**result.groupdict())
                    yield int(elapsed_time / total_dur * 100)

        if p.returncode != 0:
            raise RuntimeError("Error running command {}: {}".format(self.cmd, str("\n".join(stderr))))

        yield 100
171669
def Run(self):
    
    if not self.executable:
      logging.error('Could not locate "%s"' % self.long_name)
      return 0

    finfo = os.stat(self.executable)
    self.date = time.localtime(finfo[stat.ST_MTIME])

    logging.info('Running: %s %s </dev/null 2>&1'
                 % (self.executable, FLAGS.help_flag))
    # --help output is often routed to stderr, so we combine with stdout.
    # Re-direct stdin to /dev/null to encourage programs that
    # don't understand --help to exit.
    (child_stdin, child_stdout_and_stderr) = os.popen4(
      [self.executable, FLAGS.help_flag])
    child_stdin.close()       # '</dev/null'
    self.output = child_stdout_and_stderr.readlines()
    child_stdout_and_stderr.close()
    if len(self.output) < _MIN_VALID_USAGE_MSG:
      logging.error('Error: "%s %s" returned only %d lines: %s'
                    % (self.name, FLAGS.help_flag,
                       len(self.output), self.output))
      return 0
    return 1
1165952
def run_and_capture(*args, **kwargs)
      ret = _wrap_run((proc { |*a, **k| Host.run_and_capture(*a, **k) }), *args, **kwargs)
      @last_err = ret[:err]
      @last_out = ret[:out]
      ret
    end
1129610
def monitor_running_process(context: RunContext):
    
    while True:
        capture_output_from_running_process(context)

        if context.process_finished():
            context.return_code = context.command.returncode
            break

        if context.process_timed_out():
            context.return_code = -1
            raise ProcessTimeoutError(
                exe_name=context.exe_short_name,
                timeout=context.timeout,
            )
1256279
def run(self, command, env={}, path=None,
            uid=None, gid=None, usePTY=0, childFDs=None):
        
        deferred = defer.Deferred()
        processProtocol = _SummaryProcessProtocol(deferred)
        d = defer.maybeDeferred(self.execute, processProtocol, command, env,
                                path, uid, gid, usePTY, childFDs)
        d.addErrback(deferred.errback)
        return deferred
450476
def perform_command(self):
        
        if len(self.actual_arguments) < 2:
            return self.print_help()
        audio_file_path = self.actual_arguments[0]
        mode = self.actual_arguments[1]
        if mode not in [u"speech", u"nonspeech", u"both"]:
            return self.print_help()
        output_file_path = None
        if len(self.actual_arguments) >= 3:
            output_file_path = self.actual_arguments[2]
        output_time = not self.has_option([u"-i", u"--index"])

        self.check_c_extensions("cmfcc")
        if not self.check_input_file(audio_file_path):
            return self.ERROR_EXIT_CODE
        if (output_file_path is not None) and (not self.check_output_file(output_file_path)):
            return self.ERROR_EXIT_CODE

        self.print_info(u"Reading audio...")
        try:
            audio_file_mfcc = AudioFileMFCC(audio_file_path, rconf=self.rconf, logger=self.logger)
        except AudioFileConverterError:
            self.print_error(u"Unable to call the ffmpeg executable '%s'" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]))
            self.print_error(u"Make sure the path to ffmpeg is correct")
            return self.ERROR_EXIT_CODE
        except (AudioFileUnsupportedFormatError, AudioFileNotInitializedError):
            self.print_error(u"Cannot read file '%s'" % (audio_file_path))
            self.print_error(u"Check that its format is supported by ffmpeg")
            return self.ERROR_EXIT_CODE
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while reading the audio file:")
            self.print_error(u"%s" % exc)
            return self.ERROR_EXIT_CODE
        self.print_info(u"Reading audio... done")

        self.print_info(u"Executing VAD...")
        audio_file_mfcc.run_vad()
        self.print_info(u"Executing VAD... done")

        speech = audio_file_mfcc.intervals(speech=True, time=output_time)
        nonspeech = audio_file_mfcc.intervals(speech=False, time=output_time)
        if mode == u"speech":
            if output_time:
                intervals = [(i.begin, i.end) for i in speech]
                template = u"%.3f\t%.3f"
            else:
                intervals = speech
                template = u"%d\t%d"
        elif mode == u"nonspeech":
            if output_time:
                intervals = [(i.begin, i.end) for i in nonspeech]
                template = u"%.3f\t%.3f"
            else:
                intervals = nonspeech
                template = u"%d\t%d"
        elif mode == u"both":
            if output_time:
                speech = [(i.begin, i.end, u"speech") for i in speech]
                nonspeech = [(i.begin, i.end, u"nonspeech") for i in nonspeech]
                template = u"%.3f\t%.3f\t%s"
            else:
                speech = [(i[0], i[1], u"speech") for i in speech]
                nonspeech = [(i[0], i[1], u"nonspeech") for i in nonspeech]
                template = u"%d\t%d\t%s"
            intervals = sorted(speech + nonspeech)
        self.write_to_file(output_file_path, intervals, template)

        return self.NO_ERROR_EXIT_CODE
955037
def run_progress
      if counts_set? && total_count > 0
        sum = output.values_at(:success_count, :cancelled_count, :failed_count).reduce(:+)
        sum.to_f / total_count
      else
        0.1
      end
    end
236835
function runFfprobe(command) {
  const inputProbeIndex = 0;
  if (command._inputs[inputProbeIndex].isStream) {
    // Don't probe input streams as this will consume them
    return;
  }
  command.ffprobe(inputProbeIndex, function(err, data) {
    command._ffprobeData = data;
  });
}
782424
def subprocess_output(command, raise_on_empty_output):
    

    # Use tempfile, allowing a larger amount of memory. The subprocess.Popen
    # docs warn that the data read is buffered in memory. They suggest not to
    # use subprocess.PIPE if the data size is large or unlimited.
    with tempfile.TemporaryFile() as stdout_f, tempfile.TemporaryFile() as stderr_f:
        proc = subprocess.Popen(command, stdout=stdout_f, stderr=stderr_f)
        proc.wait()
        stderr_f.seek(0)
        err = stderr_f.read()
        stdout_f.seek(0)
        output = stdout_f.read()

    if not output and raise_on_empty_output:
        raise SubprocessOutputEmptyError("get_subprocess_output expected output but had none.")

    return output, err, proc.returncode
440399
def main():
    """"""
    options = docopt(__doc__, version=__version__)
    if options['segment']:
        segment(
            options['<file>'],
            options['--output'],
            options['--target-duration'],
            options['--mpegts'],
        )
110956
def run(self):
        '''
        
        '''

        self._log('About to perform NifTI to %s conversion...\n' %
                  self._str_outputFileType)

        frames     = 1
        frameStart = 0
        frameEnd   = 0

        sliceStart = 0
        sliceEnd   = 0

        if self._b_4D:
            self._log('4D volume detected.\n')
            frames = self._Vnp_4DVol.shape[3]
        if self._b_3D:
            self._log('3D volume detected.\n')

        if self._b_convertMiddleFrame:
            self._frameToConvert = int(frames/2)

        if self._frameToConvert == -1:
            frameEnd    = frames
        else:
            frameStart  = self._frameToConvert
            frameEnd    = self._frameToConvert + 1

        for f in range(frameStart, frameEnd):
            if self._b_4D:
                self._Vnp_3DVol = self._Vnp_4DVol[:,:,:,f]
            slices     = self._Vnp_3DVol.shape[2]
            if self._b_convertMiddleSlice:
                self._sliceToConvert = int(slices/2)

            if self._sliceToConvert == -1:
                sliceEnd    = -1
            else:
                sliceStart  = self._sliceToConvert
                sliceEnd    = self._sliceToConvert + 1

            misc.mkdir(self._str_outputDir)
            if self._b_reslice:
                for dim in ['x', 'y', 'z']:
                    self.dim_save(dimension = dim, makeSubDir = True, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
            else:
                self.dim_save(dimension = 'z', makeSubDir = False, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
305953
def cmd_fft(args):
    ''''''
    from MAVProxy.modules.lib import mav_fft
    if len(args) > 0:
        condition = args[0]
    else:
        condition = None
    child = multiproc.Process(target=mav_fft.mavfft_display, args=[mestate.filename,condition])
    child.start()
788515
def get_output(cmd, args):
    
    from subprocess import Popen, STDOUT, PIPE

    command = [cmd]
    command.extend(listify(args))

    process = Popen(command, stdout=PIPE, stderr=STDOUT)
    out, _ = process.communicate()

    return out.decode('utf-8')
559032
async def checked_run(*cmd):
  

  # Start the subprocess.
  logging.info('Running: %s', expand_cmd_str(cmd))
  with logged_timer('{} finished'.format(get_cmd_name(cmd))):
    p = await asyncio.create_subprocess_exec(
        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)

    # Stream output from the process stdout.
    chunks = []
    while True:
      chunk = await p.stdout.read(16 * 1024)
      if not chunk:
        break
      chunks.append(chunk)

    # Wait for the process to finish, check it was successful & build stdout.
    await p.wait()
    stdout = b''.join(chunks).decode()[:-1]
    if p.returncode:
      raise RuntimeError('Return code {} from process: {}\n{}'.format(
          p.returncode, expand_cmd_str(cmd), stdout))

    return stdout
427979
def progress(count, total, suffix=''):
    '''
    
    '''
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))
    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)
    sys.stdout.write('[%s] %s%s %s\r' % (bar, percents, '%', suffix))
    sys.stdout.flush()
1259458
def perform_command(self):
        
        if len(self.actual_arguments) < 2:
            return self.print_help()
        input_file_path = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        output_text_format = self.has_option_with_value(u"--format")
        if output_text_format is None:
            output_text_format = u"%.18e"
        output_binary = self.has_option([u"-b", u"--binary"])
        output_npz = self.has_option([u"-z", u"--npz"])
        output_npy = self.has_option([u"-n", u"--npy"])
        delete_first = self.has_option([u"-d", u"--delete-first"])
        transpose = self.has_option([u"-t", u"--transpose"])

        self.check_c_extensions("cmfcc")
        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        try:
            mfccs = AudioFileMFCC(input_file_path, rconf=self.rconf, logger=self.logger).all_mfcc
            if delete_first:
                mfccs = mfccs[1:, :]
            if transpose:
                mfccs = mfccs.transpose()
            if output_binary:
                # save as a raw C float64 binary file
                mapped = numpy.memmap(output_file_path, dtype="float64", mode="w+", shape=mfccs.shape)
                mapped[:] = mfccs[:]
                mapped.flush()
                del mapped
            elif output_npz:
                # save as a .npz compressed binary file
                with io.open(output_file_path, "wb") as output_file:
                    numpy.savez(output_file, mfccs)
            elif output_npy:
                # save as a .npy binary file
                with io.open(output_file_path, "wb") as output_file:
                    numpy.save(output_file, mfccs)
            else:
                # save as a text file
                # NOTE: in Python 2, passing the fmt value a Unicode string crashes NumPy
                #       hence, converting back to bytes, which works in Python 3 too
                numpy.savetxt(output_file_path, mfccs, fmt=gf.safe_bytes(output_text_format))
            self.print_info(u"MFCCs shape: %d %d" % (mfccs.shape))
            self.print_success(u"MFCCs saved to '%s'" % (output_file_path))
            return self.NO_ERROR_EXIT_CODE
        except AudioFileConverterError:
            self.print_error(u"Unable to call the ffmpeg executable '%s'" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]))
            self.print_error(u"Make sure the path to ffmpeg is correct")
        except (AudioFileUnsupportedFormatError, AudioFileNotInitializedError):
            self.print_error(u"Cannot read file '%s'" % (input_file_path))
            self.print_error(u"Check that its format is supported by ffmpeg")
        except OSError:
            self.print_error(u"Cannot write file '%s'" % (output_file_path))

        return self.ERROR_EXIT_CODE
1180651
def run(self):
        
        self._logger.info("running for <{url}>".format(url=self._url))

        args = format_args(self._options)
        self._logger.debug("command: `{cmd}` / args: {args}".
                           format(cmd=self._cmd, args=args))

        # run the process
        try:
            process = Popen(
                args=[self._cmd] + args,
                stdin=PIPE,
                stdout=PIPE,
                stderr=PIPE
            )

            pid = process.pid
            self._logger.debug("running as PID #{pid}".format(pid=pid))
        except OSError as ex:
            raise PhantomasRunError(
                "Failed to run phantomas: {0}".format(ex), ex.errno)

        # wait to complete
        try:
            stdout, stderr = process.communicate()
            returncode = process.returncode
        except Exception:
            raise PhantomasRunError("Failed to complete the run")

        # for Python 3.x - decode bytes to string
        stdout = stdout.decode('utf8')
        stderr = stderr.decode('utf8')

        # check the response code
        self._logger.debug("completed with return code #{returncode}".
                           format(returncode=returncode))

        if stderr != '':
            self._logger.debug("stderr: {stderr}".format(stderr=stderr))

            raise PhantomasFailedError(stderr.strip(), returncode)

        # try parsing the response
        try:
            results = json.loads(stdout)
        except Exception:
            raise PhantomasResponseParsingError("Unable to parse the response")

        if self._options.get("runs", 0) > 1:
            return Runs(self._url, results)
        else:
            return Results(self._url, results)