Python sys.__stdout__() Examples

The following are 30 code examples for showing how to use sys.__stdout__(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: pyscf   Author: pyscf   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def testfile(self):
        try:
            with open(self.filename) as fd:
                exec(compile(fd.read(), self.filename, 'exec'), {})
        except KeyboardInterrupt:
            raise RuntimeError('Keyboard interrupt')
        except ImportError as ex:
            module = ex.args[0].split()[-1].replace("'", '').split('.')[0]
            if module in ['scipy', 'matplotlib', 'Scientific', 'lxml',
                          'flask', 'argparse']:
                sys.__stdout__.write('skipped (no {0} module) '.format(module))
            else:
                raise
        except NotAvailable as notavailable:
            sys.__stdout__.write('skipped ')
            msg = str(notavailable)
            if msg:
                sys.__stdout__.write('({0}) '.format(msg)) 
Example 2
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    License: GNU General Public License v3.0 6 votes vote down vote up
def write(self,text):
        proceed = 1
        lineNo = 0
        addText = ''
        if self.func != None:
            proceed,lineNo,newText = self.func(text)
            if proceed:
            	if text.split() == []:
            		self.origOut.write(text)
            	else:
                #if goint to stdout then only add line no file etc
                #for stderr it is already there
                    if self.out:
                    	if lineNo:
                            try:
               			raise "Dummy"
               	            except:
               			newText =  'line('+str(sys.exc_info()[2].tb_frame.f_back.f_lineno)+'):'+newText
               			codeObject = sys.exc_info()[2].tb_frame.f_back.f_code
              			fileName = codeObject.co_filename
              			funcName = codeObject.co_name
                    	self.origOut.write('file '+fileName+','+'func '+funcName+':')
                	self.origOut.write(newText)
    #pass all other methods to __stdout__ so that we don't have to override them 
Example 3
Project: ec2-api   Author: openstack   File: colorizer.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, stream, descriptions, verbosity):
        super(EC2ApiTestResult, self).__init__()
        self.stream = stream
        self.showAll = verbosity > 1
        self.num_slow_tests = 10
        self.slow_tests = []  # this is a fixed-sized heap
        self.colorizer = None
        # NOTE(vish): reset stdout for the terminal check
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
            if colorizer.supported():
                self.colorizer = colorizer(self.stream)
                break
        sys.stdout = stdout
        self.start_time = None
        self.last_time = {}
        self.results = {}
        self.last_written = None 
Example 4
Project: phpsploit   Author: nil0x42   File: wrapper.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, outfile=sys.__stdout__, backlog=False):
        # get original stdout
        self._orig_outfile = outfile

        # just in case we wrap at runtime o the future,
        # as we did with `colorama_wrapper` in the past
        self.outfile = self._orig_outfile

        # handle back logging
        self._backlog = StringIO()
        if backlog:
            self._has_backlog = True
        else:
            self._has_backlog = False

        # are colors supported ?
        self._has_colors = ui.output.colors()

        self._write_lock = False 
Example 5
Project: daf-recipes   Author: italia   File: test_coding_standards.py    License: GNU General Public License v3.0 6 votes vote down vote up
def find_pep8_errors(cls, filename=None, lines=None):
        try:
            sys.stdout = cStringIO.StringIO()
            config = {}

            # Ignore long lines on test files, as the test names can get long
            # when following our test naming standards.
            if cls._is_test(filename):
                config['ignore'] = ['E501']

            checker = pep8.Checker(filename=filename, lines=lines,
                                   **config)
            checker.check_all()
            output = sys.stdout.getvalue()
        finally:
            sys.stdout = sys.__stdout__

        errors = []
        for line in output.split('\n'):
            parts = line.split(' ', 2)
            if len(parts) == 3:
                location, error, desc = parts
                line_no = location.split(':')[1]
                errors.append('%s ln:%s %s' % (error, line_no, desc))
        return errors 
Example 6
Project: paper.io.sessdsa   Author: chbpku   File: compN17Quarterfinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):    # 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 8:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 四分之一决赛 
Example 7
Project: paper.io.sessdsa   Author: chbpku   File: compF17Semifinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):# 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 2:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 半决赛 
Example 8
Project: paper.io.sessdsa   Author: chbpku   File: 1.compF17Quarterfinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):    # 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 8:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 四分之一决赛 
Example 9
Project: paper.io.sessdsa   Author: chbpku   File: 3.compF17Semifinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):# 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 2:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 半决赛 
Example 10
Project: paper.io.sessdsa   Author: chbpku   File: 4.compN17Semifinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):# 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 8:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 半决赛 
Example 11
Project: paper.io.sessdsa   Author: chbpku   File: compF17Quarterfinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):    # 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 8:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 四分之一决赛 
Example 12
Project: paper.io.sessdsa   Author: chbpku   File: compN17Semifinal.py    License: GNU General Public License v3.0 6 votes vote down vote up
def quarterfinal(FOLDER):# 读取文件夹内的算法
    PLRS = []
    
    sys.path.append(os.path.abspath(FOLDER))    # 将AI文件夹加入环境路径
    for file in os.listdir(FOLDER):
        if file.endswith('.py') and len(PLRS) < 8:
            # 提取play函数
            try:
                name = file[:-3]
                ai = __import__(name)
                ai.play
                PLRS.append((name, ai))

            # 读取时出错
            except Exception as e:
                print('读取%r时出错:%s' % (file, e), file=sys.__stdout__)

    return PLRS


# 半决赛 
Example 13
def cur_status():
    firstRowOfTable = [' ']
    for i in range(len(players)):
        firstRowOfTable += [players[i][0]]
    x = PrettyTable(firstRowOfTable + ['Score'])

    for i in range(len(players)):
        x.add_row([players[i][0]] + boardRaw[i] + [board[i][4]])
        x.add_row([' '] * (len(players) + 2))

    os.system('clear')
    print(x, file=sys.__stdout__)

    # 积分条
    out = sorted(board, key=itemgetter(-1, 1, 0), reverse=True)
    for i in range(len(out)):
        print(
            '%15s%3d %s' % (out[i][0], out[i][-1], "----" * out[i][-1]),
            file=sys.__stdout__) 
Example 14
Project: sphinx-execute-code   Author: jpsenior   File: __init__.py    License: MIT License 5 votes vote down vote up
def execute_code(cls, code):
        """ Executes supplied code as pure python and returns a list of stdout, stderr

        Args:
            code (string): Python code to execute

        Results:
            (list): stdout, stderr of executed python code

        Raises:
            ExecutionError when supplied python is incorrect

        Examples:
            >>> execute_code('print "foobar"')
            'foobar'
        """

        output = StringIO.StringIO()
        err = StringIO.StringIO()

        sys.stdout = output
        sys.stderr = err

        try:
            # pylint: disable=exec-used
            exec(code)
        # If the code is invalid, just skip the block - any actual code errors
        # will be raised properly
        except TypeError:
            pass
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

        results = list()
        results.append(output.getvalue())
        results.append(err.getvalue())
        results = ''.join(results)

        return results 
Example 15
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Start(self,func=None):
    	if self.out:
            sys.stdout = self
            self.origOut = sys.__stdout__
        else:
       	    sys.stderr= self
            self.origOut = sys.__stderr__
        if func:
            self.func = func
        else:
            self.func = self.TestHook
    #Stop will stop routing of print statements thru this class 
Example 16
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Stop(self):
    	self.origOut.flush()
    	if self.out:
            sys.stdout = sys.__stdout__
        else:
            sys.stderr = sys.__stderr__
            self.func = None
    #override write of stdout 
Example 17
Project: razzy-spinner   Author: rafasashi   File: internals.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _decode_stdoutdata(stdoutdata):
    """ Convert data read from stdout/stderr to unicode """
    if not isinstance(stdoutdata, bytes):
        return stdoutdata
    
    encoding = getattr(sys.__stdout__, "encoding", locale.getpreferredencoding())
    if encoding is None:
        return stdoutdata.decode()
    return stdoutdata.decode(encoding)

##########################################################################
# Import Stdlib Module
########################################################################## 
Example 18
Project: recruit   Author: Frank-qlu   File: console.py    License: Apache License 2.0 5 votes vote down vote up
def __dir__(self):
        return dir(sys.__stdout__) 
Example 19
Project: recruit   Author: Frank-qlu   File: console.py    License: Apache License 2.0 5 votes vote down vote up
def __getattribute__(self, name):
        if name == "__members__":
            return dir(sys.__stdout__)
        try:
            stream = _local.stream
        except AttributeError:
            stream = sys.__stdout__
        return getattr(stream, name) 
Example 20
Project: recruit   Author: Frank-qlu   File: console.py    License: Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return repr(sys.__stdout__)


# add the threaded stream as display hook 
Example 21
Project: don   Author: CiscoSystems   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def debug(msg):
    if settings['debug']:
        if not sys.stdout == sys.__stdout__:
            tmp = sys.stdout
            sys.stdout = sys.__stdout__
            print('DEBUG: ' + msg)
            sys.stdout = tmp
        else:
            print('DEBUG: ' + msg) 
Example 22
Project: don   Author: CiscoSystems   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def error(msg):
    if not sys.stdout == sys.__stdout__:
        tmp = sys.stdout
        sys.stdout = sys.__stdout__
        print('ERROR: ' + msg)
        sys.stdout = tmp
    else:
        print('ERROR: ' + msg) 
Example 23
Project: don   Author: CiscoSystems   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def warning(msg):
    if not sys.stdout == sys.__stdout__:
        tmp = sys.stdout
        sys.stdout = sys.__stdout__
        print('WARNING: ' + msg)
        sys.stdout = tmp
    else:
        print('WARNING: ' + msg) 
Example 24
Project: don   Author: CiscoSystems   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def status_update(msg):
    # storing in log file for interactive display on UI
    log = open('collector_log.txt', 'w')
    if not sys.stdout == sys.__stdout__:
        tmp = sys.stdout
        sys.stdout = sys.__stdout__
        print('STATUS: ' + msg)
        log.write('msg')
        sys.stdout = tmp
    else:
        print('STATUS: ' + msg)
        log.write(msg) 
Example 25
Project: don   Author: CiscoSystems   File: plot.py    License: Apache License 2.0 5 votes vote down vote up
def plot_compute_node(self):
        tag = 'compute'
        redirected = False
        if sys.stdout == sys.__stdout__:
            self.outfile = open(self.compute_dot_file, "w")
            sys.stdout = self.outfile
            redirected = True
            self.__digraph_open(tag)

        # Title
        self.__cluster_open('ComputeNode', 'red')
        self.__cluster_name('Compute Node', 1, 'yellow')
        self.__cluster_close()

        # Plot nodes
        self.__cluster_open_plain('Nova')
        self.__plot_vms()
        self.__plot_linux_bridge()
        self.__cluster_close_plain()

        self.__cluster_open_plain('OVS')
        self.__plot_br_int_compute()
        self.__plot_br_tun(tag)
        self.__cluster_close_plain()

        # Plot edges
        self.__plot_title_edges(tag)
        self.__plot_vms_to_linuxbridge()
        self.__plot_linuxbridge_to_br_int()
        self.__plot_br_int_to_br_tun(tag)

        if redirected:
            self.__digraph_close()
            self.outfile.close()
            sys.stdout = sys.__stdout__ 
Example 26
Project: browserscope   Author: elsigh   File: dev_appserver.py    License: Apache License 2.0 5 votes vote down vote up
def MonkeyPatchPdb(pdb):
  """Given a reference to the pdb module, fix its set_trace function.

  This will allow the standard trick of setting a breakpoint in your
  code by inserting a call to pdb.set_trace() to work properly, as
  long as the original stdin and stdout of dev_appserver.py are
  connected to a console or shell window.
  """

  def NewSetTrace():
    """Replacement for set_trace() that uses the original i/o streams.

    This is necessary because by the time the user code that might
    invoke pdb.set_trace() runs, the default sys.stdin and sys.stdout
    are redirected to the HTTP request and response streams instead,
    so that pdb will encounter garbage (or EOF) in its input, and its
    output will garble the HTTP response.  Fortunately, sys.__stdin__
    and sys.__stderr__ retain references to the original streams --
    this is a standard Python feature.  Also, fortunately, as of
    Python 2.5, the Pdb class lets you easily override stdin and
    stdout.  The original set_trace() function does essentially the
    same thing as the code here except it instantiates Pdb() without
    arguments.
    """
    p = pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__)
    p.set_trace(sys._getframe().f_back)

  pdb.set_trace = NewSetTrace 
Example 27
Project: jbox   Author: jpush   File: console.py    License: MIT License 5 votes vote down vote up
def __dir__(self):
        return dir(sys.__stdout__) 
Example 28
Project: jbox   Author: jpush   File: console.py    License: MIT License 5 votes vote down vote up
def __getattribute__(self, name):
        if name == '__members__':
            return dir(sys.__stdout__)
        try:
            stream = _local.stream
        except AttributeError:
            stream = sys.__stdout__
        return getattr(stream, name) 
Example 29
Project: jbox   Author: jpush   File: console.py    License: MIT License 5 votes vote down vote up
def __repr__(self):
        return repr(sys.__stdout__)


# add the threaded stream as display hook 
Example 30
Project: NINJA-PingU   Author: OWASP   File: debugserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def handle(self):
    ddbg("debugserver: handling")
    try:
      self.socketio = self.request.makefile()
      sys.stdout = self.socketio
      sys.stdin = self.socketio
      sys.stderr = self.socketio
      self.console.run(self)
    finally:
      sys.stdout = sys.__stdout__
      sys.stdin = sys.__stdin__
      sys.stderr = sys.__stderr__
      self.socketio.close()
      ddbg("debugserver: done handling")