Python sys.__stdout__() Examples

The following are 30 code examples of sys.__stdout__(). 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 also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: 3.compF17Semifinal.py    From paper.io.sessdsa with 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 #2
Source File: wrapper.py    From phpsploit with 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 #3
Source File: colorizer.py    From ec2-api with 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
Source File: test_coding_standards.py    From daf-recipes with 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 #5
Source File: compN17Quarterfinal.py    From paper.io.sessdsa with 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 #6
Source File: compF17Semifinal.py    From paper.io.sessdsa with 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 #7
Source File: 1.compF17Quarterfinal.py    From paper.io.sessdsa with 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 #8
Source File: 4.compN17Semifinal.py    From paper.io.sessdsa with 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
Source File: compF17Quarterfinal.py    From paper.io.sessdsa with 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 #10
Source File: kimmo.py    From razzy-spinner with 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 #11
Source File: compN17Semifinal.py    From paper.io.sessdsa with 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
Source File: roundRobinWithScoreboard.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: __init__.py    From pyscf with 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 #14
Source File: nontrivial.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the calling frame, first restoring
    sys.stdout to the real output stream. Note that sys.stdout is NOT
    reset to whatever it was before the call once pdb is done!
    """
    import pdb
    import sys
    stdout = sys.stdout
    sys.stdout = sys.__stdout__
    pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #15
Source File: decorators.py    From Computable with MIT License 5 votes vote down vote up
def suppress_stdout(f):
    def wrapped(*args, **kwargs):
        try:
            sys.stdout = StringIO()
            f(*args, **kwargs)
        finally:
            sys.stdout = sys.__stdout__

    return wrapped 
Example #16
Source File: test_file2k.py    From oss-ftp with MIT License 5 votes vote down vote up
def testStdin(self):
        # This causes the interpreter to exit on OSF1 v5.1.
        if sys.platform != 'osf1V5':
            self.assertRaises(IOError, sys.stdin.seek, -1)
        else:
            print >>sys.__stdout__, (
                '  Skipping sys.stdin.seek(-1), it may crash the interpreter.'
                ' Test manually.')
        self.assertRaises(IOError, sys.stdin.truncate) 
Example #17
Source File: test_file.py    From BinderFilter with MIT License 5 votes vote down vote up
def testStdin(self):
        # This causes the interpreter to exit on OSF1 v5.1.
        if sys.platform != 'osf1V5':
            self.assertRaises((IOError, ValueError), sys.stdin.seek, -1)
        else:
            print((
                '  Skipping sys.stdin.seek(-1), it may crash the interpreter.'
                ' Test manually.'), file=sys.__stdout__)
        self.assertRaises((IOError, ValueError), sys.stdin.truncate) 
Example #18
Source File: test_file2k.py    From BinderFilter with MIT License 5 votes vote down vote up
def testStdin(self):
        # This causes the interpreter to exit on OSF1 v5.1.
        if sys.platform != 'osf1V5':
            self.assertRaises(IOError, sys.stdin.seek, -1)
        else:
            print >>sys.__stdout__, (
                '  Skipping sys.stdin.seek(-1), it may crash the interpreter.'
                ' Test manually.')
        self.assertRaises(IOError, sys.stdin.truncate) 
Example #19
Source File: test_parsers.py    From Computable with MIT License 5 votes vote down vote up
def test_verbose_import(self):
        text = """a,b,c,d
one,1,2,3
one,1,2,3
,1,2,3
one,1,2,3
,1,2,3
,1,2,3
one,1,2,3
two,1,2,3"""

        buf = StringIO()
        sys.stdout = buf

        try:
            # it works!
            df = self.read_csv(StringIO(text), verbose=True)
            self.assert_(buf.getvalue() == 'Filled 3 NA values in column a\n')
        finally:
            sys.stdout = sys.__stdout__

        buf = StringIO()
        sys.stdout = buf

        text = """a,b,c,d
one,1,2,3
two,1,2,3
three,1,2,3
four,1,2,3
five,1,2,3
,1,2,3
seven,1,2,3
eight,1,2,3"""

        try:
            # it works!
            df = self.read_csv(StringIO(text), verbose=True, index_col=0)
            self.assert_(buf.getvalue() == 'Filled 1 NA values in column a\n')
        finally:
            sys.stdout = sys.__stdout__ 
Example #20
Source File: nontrivial.py    From Computable with MIT License 5 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the calling frame, first restoring
    sys.stdout to the real output stream. Note that sys.stdout is NOT
    reset to whatever it was before the call once pdb is done!
    """
    import pdb
    import sys
    stdout = sys.stdout
    sys.stdout = sys.__stdout__
    pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #21
Source File: kernelapp.py    From Computable with MIT License 5 votes vote down vote up
def init_blackhole(self):
        """redirects stdout/stderr to devnull if necessary"""
        if self.no_stdout or self.no_stderr:
            blackhole = open(os.devnull, 'w')
            if self.no_stdout:
                sys.stdout = sys.__stdout__ = blackhole
            if self.no_stderr:
                sys.stderr = sys.__stderr__ = blackhole 
Example #22
Source File: run_tests.py    From mgear_core with MIT License 5 votes vote down vote up
def mute():
    try:
        sys.stdout = six.moves.StringIO()
        sys.stderr = six.moves.StringIO()
        yield

    finally:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__ 
Example #23
Source File: mock.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def check_playback(self):
        """
        Report any errors that were encounterd during calls
        to __method_playback().
        """
        if len(self.errors) > 0:
            if self._debug:
                print('\nPlayback errors:')
            for error in self.errors:
                print(error, file=sys.__stdout__)

            if self._ut:
                self._ut.fail('\n'.join(self.errors))

            raise CheckPlaybackError
        elif len(self.recording) != 0:
            errors = []
            for func_call in self.recording:
                error = "%s not called" % (func_call,)
                errors.append(error)
                print(error, file=sys.__stdout__)

            if self._ut:
                self._ut.fail('\n'.join(errors))

            raise CheckPlaybackError
        self.recording.clear() 
Example #24
Source File: mock.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def _append_error(self, error):
        if self._debug:
            print(' *** ' + error, file=sys.__stdout__)
        if self._fail_fast:
            raise CheckPlaybackError(error)
        self.errors.append(error) 
Example #25
Source File: mock.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def __method_playback(self, symbol, *args, **dargs):
        if self._debug:
            print(' * Mock call: ' + _dump_function_call(symbol, args, dargs),
                  file=sys.__stdout__)

        if len(self.recording) != 0:
            # self.recording is subscriptable (deque), ignore E1136
            func_call = self.recording[0]   # pylint: disable=E1136
            if func_call.symbol != symbol:
                msg = ("Unexpected call: %s\nExpected: %s"
                       % (_dump_function_call(symbol, args, dargs),
                          func_call))
                self._append_error(msg)
                return None

            if not func_call.match(*args, **dargs):
                msg = ("Incorrect call: %s\nExpected: %s"
                       % (_dump_function_call(symbol, args, dargs),
                          func_call))
                self._append_error(msg)
                return None

            # this is the expected call so pop it and return
            self.recording.popleft()
            if func_call.error:
                raise func_call.error
            else:
                return func_call.return_obj
        else:
            msg = ("unexpected call: %s"
                   % (_dump_function_call(symbol, args, dargs)))
            self._append_error(msg)
            return None 
Example #26
Source File: gameboard4.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

    if sys.platform.startswith("win"):
        filename = os.path.join(tempfile.gettempdir(), "gameboard.txt")
        with open(filename, "w", encoding="utf-8") as file:
            file.write(sys.stdout.getvalue())
        print("wrote '{}'".format(filename), file=sys.__stdout__) 
Example #27
Source File: core.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def parseArgs(self, argv):
        """Parse argv and env and configure running environment.
        """
        self.config.configure(argv, doc=self.usage())
        log.debug("configured %s", self.config)

        # quick outs: version, plugins (optparse would have already
        # caught and exited on help)
        if self.config.options.version:
            from nose import __version__
            sys.stdout = sys.__stdout__
            print "%s version %s" % (os.path.basename(sys.argv[0]), __version__)
            sys.exit(0)

        if self.config.options.showPlugins:
            self.showPlugins()
            sys.exit(0)

        if self.testLoader is None:
            self.testLoader = defaultTestLoader(config=self.config)
        elif isclass(self.testLoader):
            self.testLoader = self.testLoader(config=self.config)
        plug_loader = self.config.plugins.prepareTestLoader(self.testLoader)
        if plug_loader is not None:
            self.testLoader = plug_loader
        log.debug("test loader is %s", self.testLoader)

        # FIXME if self.module is a string, add it to self.testNames? not sure

        if self.config.testNames:
            self.testNames = self.config.testNames
        else:
            self.testNames = tolist(self.defaultTest)
        log.debug('defaultTest %s', self.defaultTest)
        log.debug('Test names are %s', self.testNames)
        if self.config.workingDir is not None:
            os.chdir(self.config.workingDir)
        self.createTests() 
Example #28
Source File: gameboard2.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

    if sys.platform.startswith("win"):
        filename = os.path.join(tempfile.gettempdir(), "gameboard.txt")
        with open(filename, "w", encoding="utf-8") as file:
            file.write(sys.stdout.getvalue())
        print("wrote '{}'".format(filename), file=sys.__stdout__) 
Example #29
Source File: gameboard3.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

    if sys.platform.startswith("win"):
        filename = os.path.join(tempfile.gettempdir(), "gameboard.txt")
        with open(filename, "w", encoding="utf-8") as file:
            file.write(sys.stdout.getvalue())
        print("wrote '{}'".format(filename), file=sys.__stdout__) 
Example #30
Source File: gameboard1.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

    if sys.platform.startswith("win"):
        filename = os.path.join(tempfile.gettempdir(), "gameboard.txt")
        with open(filename, "w", encoding="utf-8") as file:
            file.write(sys.stdout.getvalue())
        print("wrote '{}'".format(filename), file=sys.__stdout__)