当前位置: 首页>>代码示例>>Python>>正文


Python StringIO.StringIO方法代码示例

本文整理汇总了Python中io.StringIO.StringIO方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.StringIO方法的具体用法?Python StringIO.StringIO怎么用?Python StringIO.StringIO使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.StringIO的用法示例。


在下文中一共展示了StringIO.StringIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_log_stream

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def add_log_stream(self, stream=sys.stderr, level=logging.INFO):
        """
        Add a stream where messages are outputted to.

        @param stream: stderr/stdout or a file stream
        @type stream: file | FileIO | StringIO
        @param level: minimum level of messages to be logged
        @type level: int | long

        @return: None
        @rtype: None
        """
        assert self.is_stream(stream)
        # assert isinstance(stream, (file, io.FileIO))
        assert level in self._levelNames

        err_handler = logging.StreamHandler(stream)
        err_handler.setFormatter(self.message_formatter)
        err_handler.setLevel(level)
        self._logger.addHandler(err_handler) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:22,代码来源:loggingwrapper.py

示例2: test_str

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod()
            original_stdout = sys.stdout
            # sys.stdout = StringIO.StringIO()
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:23,代码来源:test_BackgroundSources.py

示例3: _init_psycopg2

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def _init_psycopg2(self):
        """initialize psycopg2 to use mx.DateTime for date and timestamps
        instead for datetime.datetime"""
        psycopg2 = self._native_module
        if hasattr(psycopg2, '_lc_initialized'):
            return
        psycopg2._lc_initialized = 1
        # use mxDateTime instead of datetime if available
        if HAS_MX_DATETIME:
            from psycopg2 import extensions
            extensions.register_type(psycopg2._psycopg.MXDATETIME)
            extensions.register_type(psycopg2._psycopg.MXINTERVAL)
            extensions.register_type(psycopg2._psycopg.MXDATE)
            extensions.register_type(psycopg2._psycopg.MXTIME)
            # StringIO/cStringIO adaptation
            # XXX (syt) todo, see my december discussion on the psycopg2 list
            # for a working solution
            #def adapt_stringio(stringio):
            #    print 'ADAPTING', stringio
            #    return psycopg2.Binary(stringio.getvalue())
            #import StringIO
            #extensions.register_adapter(StringIO.StringIO, adapt_stringio)
            #import cStringIO
            #extensions.register_adapter(cStringIO.StringIO, adapt_stringio) 
开发者ID:jlachowski,项目名称:clonedigger,代码行数:26,代码来源:db.py

示例4: _render

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def _render(self, mode='human', close=False):
    if close:
      return

    outfile = StringIO.StringIO() if mode == 'ansi' else sys.stdout

    row, col = self.s // self.ncol, self.s % self.ncol
    desc = self.desc.tolist()
    desc[row][col] = utils.colorize(desc[row][col], "red", highlight=True)

    outfile.write("\n".join("".join(row) for row in desc)+"\n")
    if self.lastaction is not None:
      outfile.write("  ({})\n".format(self.get_action_meanings()[self.lastaction]))
    else:
      outfile.write("\n")

    return outfile 
开发者ID:carpedm20,项目名称:deep-rl-tensorflow,代码行数:19,代码来源:corridor.py

示例5: process_gcode

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def process_gcode(self, g):
    profile = cProfile.Profile()
    self.printer.sd_card_manager.set_status(True)
    profile.enable()
    for line in self.printer.sd_card_manager:
      line = line.strip()
      if not line or line.startswith(';'):
        continue
      file_g = Gcode({"message": line})
      self.printer.processor.enqueue(file_g)
    if self.printer.sd_card_manager.get_status():
      logging.info("M24: Print from file complete")
    self.printer.sd_card_manager.set_status(False)

    self.printer.send_message(g.prot, "Done printing file")
    profile.disable()
    s = StringIO.StringIO()
    sortby = 'cumulative'
    ps = pstats.Stats(profile, stream=s).sort_stats(sortby)
    ps.print_stats()
    logging.debug(s.getvalue())
    self.printer.sd_card_manager.reset() 
开发者ID:intelligent-agent,项目名称:redeem,代码行数:24,代码来源:M2x.py

示例6: capture_logger

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def capture_logger(name):
    """ Context manager to capture a logger output with a StringIO stream.
    """
    import logging

    logger = logging.getLogger(name)
    try:
        import StringIO
        stream = StringIO.StringIO()
    except ImportError:
        from io import StringIO
        stream = StringIO()
    handler = logging.StreamHandler(stream)
    logger.addHandler(handler)
    try:
        yield stream
    finally:
        logger.removeHandler(handler) 
开发者ID:LettError,项目名称:MutatorMath,代码行数:20,代码来源:setup.py

示例7: python

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def python(self, command_or_file):
        """ Runs a python command or a python file and returns the output """
        new_stdout = StringIO.StringIO()
        old_stdout = sys.stdout
        sys.stdout = new_stdout
        new_stderr = StringIO.StringIO()
        old_stderr = sys.stderr
        sys.stderr = new_stderr
        if os.path.exists(command_or_file):
            self.send_output("[*] Running python file...")
            with open(command_or_file, 'r') as f:
                python_code = f.read()
                try:
                    exec(python_code)
                except Exception as exc:
                    self.send_output(traceback.format_exc())
        else:
            self.send_output("[*] Running python command...")
            try:
                exec(command_or_file)
            except Exception as exc:
                self.send_output(traceback.format_exc())
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        self.send_output(new_stdout.getvalue() + new_stderr.getvalue()) 
开发者ID:kaiiyer,项目名称:backnet,代码行数:27,代码来源:agent.py

示例8: testRun

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def testRun(self):
        db = DAL(DEFAULT_URI, check_reserved=['all'])
        db.define_table('person', Field('name'))
        db.define_table('pet',Field('friend',db.person),Field('name'))
        for n in range(2):
            db(db.pet).delete()
            db(db.person).delete()
            for k in range(10):
                id = db.person.insert(name=str(k))
                db.pet.insert(friend=id,name=str(k))
        db.commit()
        stream = StringIO.StringIO()
        db.export_to_csv_file(stream)
        db(db.pet).delete()
        db(db.person).delete()
        stream = StringIO.StringIO(stream.getvalue())
        db.import_from_csv_file(stream)
        assert db(db.person.id==db.pet.friend)(db.person.name==db.pet.name).count()==10
        db.pet.drop()
        db.person.drop()
        db.commit() 
开发者ID:uwdata,项目名称:termite-visualizations,代码行数:23,代码来源:test_dal.py

示例9: is_stream

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def is_stream(stream):
        """
        Test for streams

        @param stream: Any kind of stream type
        @type stream: file | io.FileIO | StringIO.StringIO

        @return: True if stream
        @rtype: bool
        """
        return hasattr(stream, 'read') and hasattr(stream, 'write') 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:13,代码来源:loggingwrapper.py

示例10: set_log_file

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def set_log_file(self, log_file, mode='a', level=logging.INFO):
        """
        Add a stream where messages are outputted to.

        @attention: file stream will only be closed if a file path is given!

        @param log_file: file stream or file path of logfile
        @type log_file: file | FileIO | StringIO | str
        @param mode: opening mode for logfile, if a file path is given
        @type mode: str
        @param level: minimum level of messages to be logged
        @type level: int or long

        @return: None
        @rtype: None
        """
        assert isinstance(log_file, str) or self.is_stream(log_file)
        assert level in self._levelNames

        if LoggingWrapper._map_logfile_handler[self._label] is not None:
            self._logger.removeHandler(LoggingWrapper._map_logfile_handler[self._label])
            LoggingWrapper._map_logfile_handler[self._label].close()
            LoggingWrapper._map_logfile_handler[self._label] = None

        if self.is_stream(log_file):
            self.add_log_stream(stream=log_file, level=level)
            return

        try:
            err_handler_file = logging.FileHandler(log_file, mode)
            err_handler_file.setFormatter(self.message_formatter)
            err_handler_file.setLevel(level)
            self._logger.addHandler(err_handler_file)
            LoggingWrapper._map_logfile_handler[self._label] = err_handler_file
        except Exception:
            sys.stderr.write("[LoggingWrapper] Could not open '{}' for logging\n".format(log_file))
            return 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:39,代码来源:loggingwrapper.py

示例11: __init__

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def __init__(self, label="DefaultLogging", logfile=None, verbose=False, debug=False):
        """
        Prototype class for any class needing a logger

        @attention:

        @param logfile: file handler or file path to a log file
        @type logfile: file | FileIO | StringIO | str
        @param verbose: Not verbose means that only warnings and errors will be past to stream
        @type verbose: bool
        @param debug: Display debug messages
        @type debug: bool

        @return: None
        @rtype: None
        """
        assert isinstance(debug, bool)

        self._logger = LoggingWrapper(label, verbose=verbose)
        if logfile:
            self._logger.set_log_file(logfile, mode='a')

        self._debug = debug
        if debug:
            self._logger.set_level(self._logger.DEBUG)

        self._logfile = None
        if isinstance(logfile, str):
            self._logfile = logfile
        else:
            if hasattr(logfile, 'name'):
                self._logfile = logfile.name
        self._verbose = verbose 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:35,代码来源:loggingwrapper.py

示例12: execute_code

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
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 
开发者ID:jpsenior,项目名称:sphinx-execute-code,代码行数:41,代码来源:__init__.py

示例13: _decodeUvData

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def _decodeUvData(self, dt):
        from PIL import Image
        from io import StringIO
        uvData = dt['uv_data']
        uvShape = dt['uv_shape']
        fStream = StringIO.StringIO(uvData.decode('base64'))
        im = Image.open(fStream)
        data = np.rollaxis(np.array(im.getdata(), dtype=np.uint8), -1, 0)
        dt['uv'] = data.reshape(uvShape)
        del dt['uv_data']
        del dt['uv_shape'] 
开发者ID:soeaver,项目名称:Parsing-R-CNN,代码行数:13,代码来源:densepose_cocoeval.py

示例14: process_stats

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def process_stats(self):  # @UnusedVariable
        timings = {
            'pytest_runtest_setup': 0,
            'pytest_runtest_call': 0,
            'pytest_runtest_teardown': 0
        }
        self.global_profile.disable()
        self.global_profile.dump_stats(PROFILE_RESULTS_FILE)
        self.global_profile.enable()
        stream = StringIO.StringIO()
        stats = pstats.Stats(PROFILE_RESULTS_FILE, stream=stream)
        stats.sort_stats('cumulative').print_stats('pytest_runtest_setup', 1)
        stats.sort_stats('cumulative').print_stats('pytest_runtest_call', 1)
        stats.sort_stats('cumulative').print_stats('pytest_runtest_teardown', 1)
        for line in stream.getvalue().split('\n'):
            if re.match('.+\d+.+\d+\.\d+.+\d+\.\d+.+\d+\.\d+.+\d+\.\d+.*', line):
                line_list = [item for item in line.split(' ') if item]
                if 'pytest_runtest_setup' in line:
                   timings['pytest_runtest_setup'] = float(line_list[3])
                elif 'pytest_runtest_call' in line:
                   timings['pytest_runtest_call'] = float(line_list[3])
                elif 'pytest_runtest_teardown' in line:
                   timings['pytest_runtest_teardown'] = float(line_list[3])
        if self.mode == "deltas":
            self.export_metrics_delta(self.metrics, timings, TOASTER_TIMINGS_JSON)
        elif self.mode == "cumulative":
            self.accumulate_values_to_json(timings, TOASTER_TIMINGS_JSON) 
开发者ID:openSUSE,项目名称:salt-toaster,代码行数:29,代码来源:conftest.py

示例15: serve_pdf

# 需要导入模块: from io import StringIO [as 别名]
# 或者: from io.StringIO import StringIO [as 别名]
def serve_pdf(invoice, request):
    # Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources

    def link_callback(uri, rel):
        # use short variable names
        sUrl = settings.STATIC_URL      # Typically /static/
        sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
        mUrl = settings.MEDIA_URL       # Typically /static/media/
        mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

        # convert URIs to absolute system paths
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))

        # make sure that file exists
        if not os.path.isfile(path):
                raise Exception(
                        'media URI must start with %s or %s' % \
                        (sUrl, mUrl))
        return path

    # Render html content through html template with context
    template = get_template(settings.PDF_TEMPLATE)
    html = template.render(Context(invoice))

    # Write PDF to file
    # file = open(os.path.join(settings.MEDIA_ROOT, 'Invoice #' + str(id) + '.pdf'), "w+b")
    file = StringIO.StringIO()
    pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)

    # Return PDF document through a Django HTTP response
    file.seek(0)
    # pdf = file.read()
    # file.close()            # Don't forget to close the file handle
    return HttpResponse(file, content_type='application/pdf') 
开发者ID:SableWalnut,项目名称:wagtailinvoices,代码行数:39,代码来源:editor.py


注:本文中的io.StringIO.StringIO方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。