Run RunValidationOutputFromOptions, print profile and return exit code.
180490
def ProfileRunValidationOutputFromOptions(feed, options):
  """"""
  import cProfile
  import pstats
  # runctx will modify a dict, but not locals(). We need a way to get rv back.
  locals_for_exec = locals()
  cProfile.runctx('rv = RunValidationOutputFromOptions(feed, options)',
                  globals(), locals_for_exec, 'validate-stats')

  # Only available on Unix, http://docs.python.org/lib/module-resource.html
  import resource
  print("Time: %d seconds" % (
      resource.getrusage(resource.RUSAGE_SELF).ru_utime +
      resource.getrusage(resource.RUSAGE_SELF).ru_stime))

  # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222
  # http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely
  # available for review and use."
  def _VmB(VmKey):
    """Return size from proc status in bytes."""
    _proc_status = '/proc/%d/status' % os.getpid()
    _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
              'KB': 1024.0, 'MB': 1024.0*1024.0}

     # get pseudo file  /proc/<pid>/status
    try:
        t = open(_proc_status)
        v = t.read()
        t.close()
    except:
        raise Exception("no proc file %s" % _proc_status)
        return 0  # non-Linux?
     # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
    try:
        i = v.index(VmKey)
        v = v[i:].split(None, 3)  # whitespace
    except:
        return 0 # v is empty

    if len(v) < 3:
        raise Exception("%s" % v)
        return 0  # invalid format?
     # convert Vm value to bytes
    return int(float(v[1]) * _scale[v[2]])

  # I ran this on over a hundred GTFS files, comparing VmSize to VmRSS
  # (resident set size). The difference was always under 2% or 3MB.
  print("Virtual Memory Size: %d bytes" % _VmB('VmSize:'))

  # Output report of where CPU time was spent.
  p = pstats.Stats('validate-stats')
  p.strip_dirs()
  p.sort_stats('cumulative').print_stats(30)
  p.sort_stats('cumulative').print_callers(30)
  return locals_for_exec['rv']
1336082
def run(self, *args):
        """"""

        params = self.parser.parse_args(args)

        ct = params.code_or_term

        if ct and len(ct) < 2:
            self.error('Code country or term must have 2 or more characters length')
            return CODE_INVALID_FORMAT_ERROR

        code = ct if ct and len(ct) == 2 else None
        term = ct if ct and len(ct) > 2 else None

        try:
            countries = api.countries(self.db, code=code, term=term)
            self.display('countries.tmpl', countries=countries)
        except (NotFoundError, InvalidValueError) as e:
            self.error(str(e))
            return e.code

        return CMD_SUCCESS
884613
def print_validation_errors(result):
    
    click.echo(red('\nValidation failed:'))
    click.echo(red('-' * 40))
    messages = result.get_messages()
    for property in messages.keys():
        click.echo(yellow(property + ':'))
        for error in messages[property]:
            click.echo(red('* ' + error))
        click.echo('')
207954
def main(reraise_exceptions=False, **kwargs):
    """"""
    exit_status = 0

    try:
        cli.main(**kwargs)
    except SoftLayer.SoftLayerAPIError as ex:
        if 'invalid api token' in ex.faultString.lower():
            print("Authentication Failed: To update your credentials, use 'slcli config setup'")
            exit_status = 1
        else:
            print(str(ex))
            exit_status = 1
    except SoftLayer.SoftLayerError as ex:
        print(str(ex))
        exit_status = 1
    except exceptions.CLIAbort as ex:
        print(str(ex.message))
        exit_status = ex.code
    except Exception:
        if reraise_exceptions:
            raise

        import traceback
        print("An unexpected error has occured:")
        print(str(traceback.format_exc()))
        print("Feel free to report this error as it is likely a bug:")
        print("    https://github.com/softlayer/softlayer-python/issues")
        print("The following snippet should be able to reproduce the error")
        exit_status = 1

    sys.exit(exit_status)
365210
def run(self):
        ''''''
        with spawn_output_reader() as (stdout_capture, stdout_thread):
            with spawn_output_reader() as (stderr_capture, stderr_thread):
                context = starter_iocontext(stdout_capture, stderr_capture)
                status = self._exec(context)
        stdout_bytes = stdout_thread.join()
        stderr_bytes = stderr_thread.join()
        result = Result(status.code, stdout_bytes, stderr_bytes)
        if is_checked_error(status):
            raise StatusError(result, self)
        return result
379714
def run(self):
        ""
        arguments = self.argument_parser.parse_args()
        argspec = inspect.getargspec(arguments.func)
        vargs = []
        for arg in argspec.args:
            vargs.append(getattr(arguments, arg))
        if argspec.varargs:
            vargs.extend(getattr(arguments, argspec.varargs))
        output = arguments.func(*vargs)
        if getattr(arguments.func, '_cli_test_command', False):
            self.exit_code = 0 if output else 1
            output = ''
        if getattr(arguments.func, '_cli_no_output', False):
            output = ''
        self.formatter.format_output(output, arguments.format)
        if charmhelpers.core.unitdata._KV:
            charmhelpers.core.unitdata._KV.flush()
110665
def exit(status=0):
    
    if status == 0:
        lab.io.printf(lab.io.Colours.GREEN, "Done.")
    else:
        lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status))
    sys.exit(status)
998229
def execute_return_success(cmd):
    '''
    
    '''

    ret = _run_all(cmd)

    if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():
        msg = 'Command Failed: {0}\n'.format(cmd)
        msg += 'Return Code: {0}\n'.format(ret['retcode'])
        msg += 'Output: {0}\n'.format(ret['stdout'])
        msg += 'Error: {0}\n'.format(ret['stderr'])
        raise CommandExecutionError(msg)

    return True
932785
def run(self):
        
        while self.status != 'EXIT':
            print(self.process_input(self.get_input()))
        
        print('Bye')
879186
def check_call_no_output(args):
    
    logger = logging.getLogger(__name__)
    logger.debug("running %s", args)
    process = subprocess.Popen(
        args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    (res_stdout, res_stderr) = process.communicate()
    if process.returncode:
        res_stdout = res_stdout
        res_stderr = res_stderr
        print(res_stdout, end='')
        print(res_stderr, end='')
        raise ValueError('exit code from [{}] was [{}]'.format(" ".join(args), process.returncode))
613883
protected function validateRun()
    {
        $status = $this->process->getExitCode();
        $error  = $this->process->getErrorOutput();

        if ($status !== 0 and $error !== '') {
            throw new \RuntimeException(
                sprintf(
                    "The exit status code %s says something went wrong:\n stderr: %s\n stdout: %s\ncommand: %s.",
                    $status,
                    $error,
                    $this->process->getOutput(),
                    $this->command
                )
            );
        }
    }
1370624
def run(client, outputs, no_output, success_codes, isolation, command_line):
    """"""
    working_dir = client.repo.working_dir
    mapped_std = _mapped_std_streams(client.candidate_paths)
    factory = CommandLineToolFactory(
        command_line=command_line,
        directory=os.getcwd(),
        working_dir=working_dir,
        successCodes=success_codes,
        **{
            name: os.path.relpath(path, working_dir)
            for name, path in mapped_std.items()
        }
    )

    with client.with_workflow_storage() as wf:
        with factory.watch(
            client, no_output=no_output, outputs=outputs
        ) as tool:
            # Make sure all inputs are pulled from a storage.
            client.pull_paths_from_storage(
                *(
                    path
                    for _, path in tool.iter_input_files(client.workflow_path)
                )
            )

            returncode = call(
                factory.command_line,
                cwd=os.getcwd(),
                **{key: getattr(sys, key)
                   for key in mapped_std.keys()},
            )

            if returncode not in (success_codes or {0}):
                raise errors.InvalidSuccessCode(
                    returncode, success_codes=success_codes
                )

            sys.stdout.flush()
            sys.stderr.flush()

            wf.add_step(run=tool)
116559
def run_and_exit(command_class):
    ''''''
    cmd = command_class(sys.argv[1:])
    if cmd.error:
        print('error: {0}'.format(cmd.error))
        sys.exit(1)
    else:
        sys.exit(cmd.run())
475595
def RunValidationOutputToFile(feed, options, output_file):
  """"""
  accumulator = HTMLCountingProblemAccumulator(options.limit_per_type,
                                               options.error_types_ignore_list)
  problems = transitfeed.ProblemReporter(accumulator)
  schedule, exit_code = RunValidation(feed, options, problems)
  if isinstance(feed, basestring):
    feed_location = feed
  else:
    feed_location = getattr(feed, 'name', repr(feed))
  accumulator.WriteOutput(feed_location, output_file, schedule, options.extension)
  return exit_code
635653
def run(self, output=None, error=None):
        

        pylint_output = output if output is not None else sys.stdout
        pylint_error = error if error is not None else sys.stderr
        savedout, savederr = sys.__stdout__, sys.__stderr__
        sys.stdout = pylint_output
        sys.stderr = pylint_error

        pylint_files = self.get_files_from_dir(os.curdir)
        self._print_line(
            "Using pylint "
            + colorama.Fore.RED
            + pylint.__version__
            + colorama.Fore.RESET
            + " for python "
            + colorama.Fore.RED
            + PYTHON_VERSION
            + colorama.Fore.RESET
        )

        self._print_line("pylint running on the following files:")
        for pylint_file in pylint_files:
            # we need to recast this as a string, else pylint enters an endless recursion
            split_file = str(pylint_file).split("/")
            split_file[-1] = colorama.Fore.CYAN + split_file[-1] + colorama.Fore.RESET
            pylint_file = "/".join(split_file)
            self._print_line("- " + pylint_file)
        self._print_line("----")

        if not self._is_using_default_rcfile():
            self.args += ["--rcfile={}".format(self.rcfile)]

        exit_kwarg = {"do_exit": False}

        run = pylint.lint.Run(self.args + pylint_files, **exit_kwarg)
        sys.stdout = savedout
        sys.stderr = savederr

        sys.exit(run.linter.msg_status)
920375
def run_cleanup(self, env, exit_code):
        """"""
        output = []
        if self.pipeline.data.hooks and len(self.pipeline.data.hooks.cleanup) > 0:
            env.update({'PIPELINE_RESULT': 'FAILURE'})
            env.update({'PIPELINE_SHELL_EXIT_CODE': str(exit_code)})
            config = ShellConfig(script=self.pipeline.data.hooks.cleanup,
                                 model=self.pipeline.model, env=env,
                                 dry_run=self.pipeline.options.dry_run,
                                 debug=self.pipeline.options.debug,
                                 strict=self.pipeline.options.strict,
                                 temporary_scripts_path=self.pipeline.options.temporary_scripts_path)
            cleanup_shell = Bash(config)
            for line in cleanup_shell.process():
                output.append(line)
                self.logger.info(" | %s", line)
        return output
799257
def print_results(results):
    
    if not isinstance(results, list):
        results = [results]

    for r in results:
        try:
            r.log()
        except AttributeError:
            raise ValueError('Argument to print_results() must be a list of '
                             'FileValidationResults or ObjectValidationResults.')