`returns_output` - Returns all print output in a list.

    Capture or ignore all print output generated by a function.

    Usage:

    output = mute(returns_output=True)(module.my_func)(args)
519061
def mute(returns_output=False):
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            saved_stdout = sys.stdout
            sys.stdout = cStringIO.StringIO()
            try:
                out = func(*args, **kwargs)
                if returns_output:
                    out = sys.stdout.getvalue().strip().split()
            finally:
                sys.stdout = saved_stdout
            return out
        return wrapper
    return decorator
466858
def print_all(self, out=sys.stdout):
        
        THREAD_FUNC_NAME_LEN = 25
        THREAD_NAME_LEN = 13
        THREAD_ID_LEN = 15
        THREAD_SCHED_CNT_LEN = 10

        out.write(CRLF)
        out.write("name           tid              ttot      scnt")
        out.write(CRLF)
        for stat in self:
            out.write(StatString(stat.name).ltrim(THREAD_NAME_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.id).rtrim(THREAD_ID_LEN))            
            out.write(" " * COLUMN_GAP)
            out.write(StatString(_fft(stat.ttot)).rtrim(TIME_COLUMN_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.sched_count).rtrim(THREAD_SCHED_CNT_LEN))
            out.write(CRLF)
1256121
def print_callback(val):
    
    success = False
    try:
        # for reasons I cannot fathom, regular printing, even directly
        # to io.stdout does not work.
        # I have to intrude rather deep into IPython to make it behave
        if have_ipython:
            if InteractiveShell.initialized():
                IPython.display.publish_display_data({'text/plain':val,'text/html':'<pre>' + val + '</pre>'})
                success = True
    except:
        pass

    if not success:
        print(val)
        sys.stdout.flush()
587299
def output(self):
        
        if (self._output is None) or (len(self._output) == 0):
            result = None
        else:
            result = self._output.pop(0)
        return result
826297
def outputs(self_):
        
        outputs = {}
        for cls in classlist(self_.cls):
            for name in dir(cls):
                method = getattr(self_.self_or_cls, name)
                dinfo = getattr(method, '_dinfo', {})
                if 'outputs' not in dinfo:
                    continue
                for override, otype, idx in dinfo['outputs']:
                    if override is not None:
                        name = override
                    outputs[name] = (otype, method, idx)
        return outputs
1350293
def show_output(self, txt, device='Console'):
        
        if device == 'Console':
            print(txt)
        elif device == 'File':
            raise ('show_output to File not implemented')
        elif device == 'Function_Return':  # hacky, to run test_AI_CLI.py
            return txt
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))
1069642
def cmd_full_return(
            self,
            tgt,
            fun,
            arg=(),
            timeout=None,
            tgt_type='glob',
            ret='',
            verbose=False,
            kwarg=None,
            **kwargs):
        '''
        
        '''
        was_listening = self.event.cpub

        try:
            pub_data = self.run_job(
                tgt,
                fun,
                arg,
                tgt_type,
                ret,
                timeout,
                kwarg=kwarg,
                listen=True,
                **kwargs)

            if not pub_data:
                return pub_data

            return (self.get_cli_static_event_returns(pub_data['jid'],
                                                      pub_data['minions'],
                                                      timeout,
                                                      tgt,
                                                      tgt_type,
                                                      verbose))
        finally:
            if not was_listening:
                self.event.close_pub()
201807
def capture_output_from_running_process(context: RunContext) -> None:
    
    # Get the raw output one line at a time
    _output = context.capture.readline(block=False)

    if _output:

        line = decode_and_filter(_output, context)

        if line:
            if not context.mute:

                # Print in real time
                _LOGGER_PROCESS.debug(line)

            # Buffer the line
            context.process_output_chunks.append(line)

        # Get additional output if any
        return capture_output_from_running_process(context)

    return None
1265485
def callback(self, output, inputs=None, state=None, events=None):
        ''
        callback_set = {'output':output,
                        'inputs':inputs and inputs or dict(),
                        'state':state and state or dict(),
                        'events':events and events or dict()}
        def wrap_func(func, callback_set=callback_set, callback_sets=self._callback_sets): # pylint: disable=dangerous-default-value, missing-docstring
            callback_sets.append((callback_set, func))
            return func
        return wrap_func
390380
def stdout(self):
        
        streams = self._payload.get('streams', None)
        return streams[0] if streams is not None and len(streams) >= 1 else ''
872414
def build_output(self, fout):
        
        fout.write('\n'.join([s for s in self.out]))
762460
def print_live_output(self):
        '''
        
        '''
        if self.block:
            raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
        else:
            while self.thread.is_alive() or self.old_output_size < len(self.output) or self.old_error_size < len(self.error):
                if self._stdout is not None and len(self.output) > self.old_output_size:
                    while self.old_output_size < len(self.output):
                        self.logger.info(self.output[self.old_output_size])
                        self.old_output_size += 1

                if self._stderr is not None and len(self.error) > self.old_error_size:
                    while self.old_error_size < len(self.error):
                        self.logger.error(self.error[self.old_error_size])
                        self.old_error_size += 1
215668
def eout(s):
    

    if allow_print: 
       if con_encoding=='':
          x=sys.stdin.encoding
          if x==None: 
             b=s.encode()
          else:
             b=s.encode(x, 'ignore')
       else:
          b=s.encode(con_encoding, 'ignore')

       if sys.version_info[0]>2:
          try: # We encountered issues on ipython with Anaconda
               # and hence made this work around
             sys.stderr.buffer.write(b)
             sys.stderr.buffer.write(b'\n')
          except Exception as e: 
             sys.stderr.write(s)
             pass
       else:
          sys.stderr.write(b)

    sys.stderr.flush()

    return None
1340510
def _get_python_block_output(src, global_dict, local_dict):
    
    src = '\n'.join([l for l in src.split('\n')
                     if not l.startswith('%') and not 'plt.show()' in l])
    ret_status = True
    err = ''
    with _string_io() as s:
        try:
            exec(src, global_dict, global_dict)
        except Exception as e:
            err = str(e)
            ret_status = False
    return (ret_status, s.getvalue()+err)
624176
def safe_output(fn, opts, task, *args, **kwargs):
    
    try:
        return fn(task, *args, **kwargs)
    except Exception as e:
        if opts["skip"] is None or not isinstance(e, opts["skip"]):
            for outp in luigi.task.flatten(task.output()):
                outp.remove()
        raise
1054790
def check_output(args):
    
    proc = Popen(args, stdout=PIPE)
    out = proc.communicate()[0]
    if proc.returncode:
        raise CalledProcessError(proc.returncode, args, output=out)
    return out