TODO
        :param executable:
        :param lock:
        :param capture_stdout:
        :param capture_stderr:
        :return:
481277
def execute_with_lock(self, executable: str, lock: ConnectedConsulLockInformation, *, capture_stdout: bool=False,
                          capture_stderr: bool=False) -> Tuple[int, Optional[bytes], Optional[bytes]]:
        
        assert lock is not None
        redirects = Munch(stdout=subprocess.PIPE if capture_stdout else sys.stdout,
                         stderr=subprocess.PIPE if capture_stderr else sys.stderr)

        # Patch for when sys.stdout and sys.stderr have been reassigned (e.g. in IDE test runners)
        non_realtime_redirects: Dict[str, StringIO] = {}
        for name, redirect in redirects.items():
            if isinstance(redirect, StringIO):
                logger.warning(f"Cannot capture {name} in real-time as `sys.{name}` does not have a fileno")
                non_realtime_redirects[name] = redirect
                redirects[name] = subprocess.PIPE

        outputs = Munch(stdout=None, stderr=None)
        with lock:
            process = subprocess.Popen(executable, shell=True, stdout=redirects.stdout, stderr=redirects.stderr)
            outputs.stdout, outputs.stderr = process.communicate()

        # Second part of redirect reassignment patch
        for name, original_redirect in non_realtime_redirects.items():
            captured = outputs[name]
            getattr(sys, name).write(captured.decode("utf-8"))

        return process.returncode, \
               outputs.stdout if capture_stdout else None, \
               outputs.stderr if capture_stderr else None
986095
def _process_plugin(self, plugin):
        '''
        
        '''
        instance = plugin['instance']
        regex = plugin['regex']
        for key in self.redis_conn.scan_iter(match=regex):
            # acquire lock
            lock = self._create_lock_object(key)

            try:
                if lock.acquire(blocking=False):
                    val = self.redis_conn.get(key)
                    self._process_key_val(instance, key, val)
            except Exception:
                self.logger.error(traceback.format_exc())
                self._increment_fail_stat('{k}:{v}'.format(k=key, v=val))

                self._process_failures(key)

            # remove lock regardless of if exception or was handled ok
            if lock._held:
                self.logger.debug("releasing lock")
                lock.release()
371291
def call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
         on_error='ignore', returncode=False):
    
    # start external command process
    p = subprocess.Popen(command, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    # get outputs
    out, _ = p.communicate()

    # throw exception if process failed
    if p.returncode != 0 and on_error == 'raise':
        raise GitInvocationError('Failed to run "%s"' % " ".join(command))

    if returncode:
        return out.strip(), p.returncode
    else:
        return out.strip()
948706
def check_isolation_executable_installed(isolation_executable):
    '''
    
    '''
    cmd = [isolation_executable, '--version']
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.communicate()
        return bool(proc.returncode == 0)
    except (OSError, ValueError) as e:
        if isinstance(e, ValueError) or getattr(e, 'errno', 1) != 2:  # ENOENT, no such file or directory
            raise RuntimeError('bwrap unavailable for unexpected reason.')
        return False
1100762
def execute!
      exit_code = begin
        # Thor accesses these streams directly rather than letting them be injected, so we replace them...
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        # Run our normal Thor app the way we know and love.
        DCMetro::Cli::Application.start(ARGV)

        # Thor::Base#start does not have a return value, assume success if no exception is raised.
        0
      rescue StandardError => e
        # The ruby interpreter would pipe this to STDERR and exit 1 in the case of an unhandled exception
        b = e.backtrace
        @stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map{|s| "\tfrom #{s}"}.join("\n"))
        1
      rescue SystemExit => e
        e.status
      ensure
        # TODO: reset your app here, free up resources, etc.
        # Examples:
        # MyApp.logger.flush
        # MyApp.logger.close
        # MyApp.logger = nil
        #
        # MyApp.reset_singleton_instance_variables

        # ...then we put the streams back.
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end

      # Proxy our exit code back to the injected kernel.
      @kernel.exit(exit_code)
    end
644714
def stderrHandler(level, object, category, file, line, message):
    

    o = ""
    if object:
        o = '"' + object + '"'

    where = "(%s:%d)" % (file, line)

    # level   pid     object   cat      time
    # 5 + 1 + 7 + 1 + 32 + 1 + 17 + 1 + 15 == 80
    safeprintf(sys.stderr, '%s [%5d] %-32s %-17s %-15s ',
               getFormattedLevelName(level), os.getpid(), o, category,
               time.strftime("%b %d %H:%M:%S"))

    try:
        safeprintf(sys.stderr, '%-4s %s %s\n', "", message, where)
    except UnicodeEncodeError:
        # this can happen if message is a unicode object, convert it back into
        # a string using the UTF-8 encoding
        message = message.encode('UTF-8')
        safeprintf(sys.stderr, '%-4s %s %s\n', "", message, where)

    sys.stderr.flush()
537802
def execute!
      exit_code = begin
        # Thor accesses these streams directly rather than letting them be
        # injected, so we replace them...
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        VcoWorkflows::CLI.start(@argv)

        # Thor::Base#start does not have a return value, assume success if no
        # exception is raised.
        0
      rescue StandardError => e
        # The ruby interpreter would pipe this to STDERR and exit 1 in the
        # case of an unhandled exception
        b = e.backtrace
        b.unshift("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
        1
      ensure
        # put them back.
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end
      # Proxy exit code back to the injected kernel.
      @kernel.exit(exit_code)
    end
188574
def read_line_stderr(self, time_limit=None):
        
        if self.proc is not None:
            return self.proc.stderr.readline().decode()
        else:
            return None
623998
def get_return_code(self, stderr=STDOUT):
        
        args = shlex.split(self.cmd)
        return call(args, stdout=PIPE, stderr=stderr)
136545
def stderr(msg, silent=False):
    
    if not silent:
        print(msg, file=sys.stderr)
313416
def run_cli
      exit_code = begin
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        Codewars::CLI.start(@argv)

        0
      rescue StandardError => e
        b = e.backtrace
        @stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
        1
      rescue SystemExit => e
        e.status
      ensure
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end

      @kernel.exit(exit_code)
    end
1198972
def _handle_stderr(self, ioloop, f, count=-1):
        
        output = non_blocking_read(self._popen.stderr, count)
        if not output:
            self._popen.stderr.close()
            self._popen.stderr = None
        else:
            self._error.write(output)
            self._register_stderr(ioloop)
1159378
def _invoke(self, *params):
		
		cmd = [self.exe, '-R', self.location] + list(params)
		with reentry.in_process_context(cmd) as result:
			sys.modules['mercurial.dispatch'].run()
		stdout = result.stdio.stdout.getvalue()
		stderr = result.stdio.stderr.getvalue()
		if not result.returncode == 0:
			raise RuntimeError(stderr.strip() or stdout.strip())
		return stdout.decode('utf-8')
1270016
def _capture_stderr(callable: Callable[..., CaptureResult], *args, **kwargs) -> CaptureResult:
        
        stream = StringIO()
        with redirect_stderr(stream):
            return_value = callable(*args, **kwargs)
        assert return_value.stderr is None, "stderr appears to have already been captured"
        return CaptureResult(return_value=return_value.return_value, stdout=return_value.stdout,
                             stderr=stream.getvalue(), exception=return_value.exception)
1272383
async def ensure_process(self):
        
        # We don't want multiple requests trying to start the process at the same time
        # FIXME: Make sure this times out properly?
        # Invariant here should be: when lock isn't being held, either 'proc' is in state &
        # running, or not.
        with (await self.state['proc_lock']):
            if 'proc' not in self.state:
                # FIXME: Prevent races here
                # FIXME: Handle graceful exits of spawned processes here
                cmd = self.get_cmd()
                server_env = os.environ.copy()

                # Set up extra environment variables for process
                server_env.update(self.get_env())

                timeout = self.get_timeout()

                proc = SupervisedProcess(self.name, *cmd, env=server_env, ready_func=self._http_ready_func, ready_timeout=timeout, log=self.log)
                self.state['proc'] = proc

                try:
                    await proc.start()

                    is_ready = await proc.ready()

                    if not is_ready:
                        await proc.kill()
                        raise web.HTTPError(500, 'could not start {} in time'.format(self.name))
                except:
                    # Make sure we remove proc from state in any error condition
                    del self.state['proc']
                    raise
575080
def lock_file(f, block=False):
    
    try:
        flags = fcntl.LOCK_EX
        if not block:
            flags |= fcntl.LOCK_NB
        fcntl.flock(f.fileno(), flags)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            raise SystemExit("ERROR: %s is locked by another process." %
                             f.name)
        raise
708667
def lock
      retries = @max_retries
      while retries > 0
        begin
          @file = File.open(@file_name, File::RDWR | File::CREAT, 0644)
          @file.sync = true

          if @file.flock(File::LOCK_EX | File::LOCK_NB)
            # We have taken the lock. Write the PID into the file and leave it
            # open.
            @file.write($$)
            @file.flush
            @file.fsync
            @file.truncate(@file.pos)
            PEROBS.log.debug "Lock file #{@file_name} has been taken for " +
              "process #{$$}"

            return true
          else
            # We did not manage to take the lock file.
            if @file.mtime <= Time.now - @timeout_secs
              pid = @file.read.to_i
              PEROBS.log.info "Old lock file found for PID #{pid}. " +
                "Removing lock."
              if is_running?(pid)
                send_signal('TERM', pid)
                # Give the process 3 seconds to terminate gracefully.
                sleep 3
                # Then send a SIGKILL to ensure it's gone.
                send_signal('KILL', pid) if is_running?(pid)
              end
              @file.close
              File.delete(@file_name) if File.exist?(@file_name)
            else
              PEROBS.log.debug "Lock file #{@file_name} is taken. Trying " +
                "to get it #{retries} more times."
            end
          end
        rescue => e
          PEROBS.log.error "Cannot take lock file #{@file_name}: #{e.message}"
          return false
        end

        retries -= 1
        sleep(@pause_secs)
      end

      PEROBS.log.info "Failed to get lock file #{@file_name} due to timeout"
      false
    end