• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python moves.cStringIO类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.moves.cStringIO的典型用法代码示例。如果您正苦于以下问题:Python cStringIO类的具体用法?Python cStringIO怎么用?Python cStringIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: __str__

 def __str__(self):
     from six.moves import cStringIO as StringIO
     temp_file = StringIO()
     for order in self:
         temp_file.write("%s\n" % str(order))
     #temp_file.write("%s\n" % str(self.head_order))
     return temp_file.getvalue()
开发者ID:dyn4mik3,项目名称:OrderBook,代码行数:7,代码来源:orderlist.py


示例2: run_model

def run_model(prob, ignore_exception=False):
    """
    Call `run_model` on problem and capture output.

    Parameters
    ----------
    prob : Problem
        an instance of Problem
    ignore_exception : bool
        Set to True to ignore an exception of any kind.

    Returns
    -------
    string
        output from calling `run_model` on the Problem, captured from stdout
    """
    stdout = sys.stdout
    strout = StringIO()

    sys.stdout = strout
    try:
        prob.run_model()
    except Exception:
        if not ignore_exception:
            exc = sys.exc_info()
            reraise(*exc)
    finally:
        sys.stdout = stdout

    return strout.getvalue()
开发者ID:OpenMDAO,项目名称:OpenMDAO,代码行数:30,代码来源:general_utils.py


示例3: test_debug_print_option_totals_color

    def test_debug_print_option_totals_color(self):

        prob = Problem()
        prob.model = FanInGrouped()
        prob.model.linear_solver = LinearBlockGS()
        prob.model.sub.linear_solver = LinearBlockGS()

        prob.model.add_design_var('iv.x1', parallel_deriv_color='par_dv')
        prob.model.add_design_var('iv.x2', parallel_deriv_color='par_dv')
        prob.model.add_design_var('iv.x3')
        prob.model.add_objective('c3.y')

        prob.driver.options['debug_print'] = ['totals']

        prob.setup(check=False, mode='fwd')
        prob.set_solver_print(level=0)
        prob.run_driver()

        indep_list = ['iv.x1', 'iv.x2', 'iv.x3']
        unknown_list = ['c3.y']

        stdout = sys.stdout
        strout = StringIO()
        sys.stdout = strout
        try:
            _ = prob.compute_totals(unknown_list, indep_list, return_format='flat_dict',
                                    debug_print=not prob.comm.rank)
        finally:
            sys.stdout = stdout

        output = strout.getvalue()

        if not prob.comm.rank:
            self.assertTrue('Solving color: par_dv (iv.x1, iv.x2)' in output)
            self.assertTrue('Solving variable: iv.x3' in output)
开发者ID:OpenMDAO,项目名称:OpenMDAO,代码行数:35,代码来源:test_parallel_derivatives.py


示例4: _MiniPPrinter

class _MiniPPrinter(object):
    def __init__(self):
        self._out = StringIO()
        self.indentation = 0

    def text(self, text):
        self._out.write(text)

    def breakable(self, sep=" "):
        self._out.write(sep)

    def begin_group(self, _, text):
        self.text(text)

    def end_group(self, _, text):
        self.text(text)

    def pretty(self, obj):
        if hasattr(obj, "_repr_pretty_"):
            obj._repr_pretty_(self, False)
        else:
            self.text(repr(obj))

    def getvalue(self):
        return self._out.getvalue()
开发者ID:gyenney,项目名称:Tools,代码行数:25,代码来源:util.py


示例5: test_basic_single_default_hook

    def test_basic_single_default_hook(self):

        _stdout = StringIO()

        class RootController(object):
            @expose()
            def index(self):
                return 'Hello, World!'

        app = TestApp(
            make_app(
                RootController(), hooks=lambda: [
                    RequestViewerHook(writer=_stdout)
                ]
            )
        )
        response = app.get('/')

        out = _stdout.getvalue()

        assert response.status_int == 200
        assert response.body == b_('Hello, World!')
        assert 'path' in out
        assert 'method' in out
        assert 'status' in out
        assert 'method' in out
        assert 'params' in out
        assert 'hooks' in out
        assert '200 OK' in out
        assert "['RequestViewerHook']" in out
        assert '/' in out
开发者ID:JNRowe-retired,项目名称:pecan,代码行数:31,代码来源:test_hooks.py


示例6: test_single_blacklist_item

    def test_single_blacklist_item(self):

        _stdout = StringIO()

        class RootController(object):
            @expose()
            def index(self):
                return 'Hello, World!'

        app = TestApp(
            make_app(
                RootController(),
                hooks=lambda: [
                    RequestViewerHook(
                        config={'blacklist': ['/']}, writer=_stdout
                    )
                ]
            )
        )
        response = app.get('/')

        out = _stdout.getvalue()

        assert response.status_int == 200
        assert response.body == b_('Hello, World!')
        assert out == ''
开发者ID:JNRowe-retired,项目名称:pecan,代码行数:26,代码来源:test_hooks.py


示例7: __call__

        def __call__(self, environ, start_response):
            try:
                return self.app(environ, start_response)
            except Exception as exc:
                # get a formatted exception
                out = StringIO()
                print_exc(file=out)
                LOG.exception(exc)

                # get formatted WSGI environment
                formatted_environ = pformat(environ)

                # render our template
                result = debug_template.render(
                    traceback=out.getvalue(),
                    environment=formatted_environ
                )

                # construct and return our response
                response = Response()
                if isinstance(exc, HTTPException):
                    response.status_int = exc.status
                else:
                    response.status_int = 500
                response.unicode_body = result
                return response(environ, start_response)
开发者ID:adamchainz,项目名称:pecan,代码行数:26,代码来源:debug.py


示例8: test_auto_cleanup_verbose

 def test_auto_cleanup_verbose(self):
     p = Poll.objects.create(
         question="Will this be deleted?", pub_date=datetime.now()
     )
     self.assertEqual(Poll.history.all().count(), 1)
     p.save()
     p.question = "Maybe this one won't...?"
     p.save()
     self.assertEqual(Poll.history.all().count(), 3)
     out = StringIO()
     management.call_command(
         self.command_name,
         "tests.poll",
         auto=True,
         verbosity=2,
         stdout=out,
         stderr=StringIO(),
     )
     self.assertEqual(
         out.getvalue(),
         "<class 'simple_history.tests.models.Poll'> has 3 historical entries\n"
         "Removed 1 historical records for "
         "<class 'simple_history.tests.models.Poll'>\n",
     )
     self.assertEqual(Poll.history.all().count(), 2)
开发者ID:treyhunner,项目名称:django-simple-history,代码行数:25,代码来源:test_commands.py


示例9: resize_avatar

def resize_avatar(image_data):
    AVATAR_SIZE = 100
    im = Image.open(StringIO(image_data))
    im = ImageOps.fit(im, (AVATAR_SIZE, AVATAR_SIZE), Image.ANTIALIAS)
    out = StringIO()
    im.save(out, format='png')
    return out.getvalue()
开发者ID:Croolis,项目名称:zulip,代码行数:7,代码来源:upload.py


示例10: test_logging_setup_with_config_obj

    def test_logging_setup_with_config_obj(self):
        class RootController(object):
            @expose()
            def index(self):
                import logging
                logging.getLogger('pecantesting').info('HELLO WORLD')
                return "HELLO WORLD"

        f = StringIO()

        from pecan.configuration import conf_from_dict
        app = TestApp(make_app(RootController(), logging=conf_from_dict({
            'loggers': {
                'pecantesting': {
                    'level': 'INFO', 'handlers': ['memory']
                }
            },
            'handlers': {
                'memory': {
                    'level': 'INFO',
                    'class': 'logging.StreamHandler',
                    'stream': f
                }
            }
        })))

        app.get('/')
        assert f.getvalue() == 'HELLO WORLD\n'
开发者ID:cleverdevil,项目名称:pecan,代码行数:28,代码来源:test_base.py


示例11: test_auto_dry_run

    def test_auto_dry_run(self):
        p = Poll.objects.create(
            question="Will this be deleted?", pub_date=datetime.now()
        )
        p.save()

        # not related to dry_run test, just for increasing coverage :)
        # create instance with single-entry history older than "minutes"
        # so it is skipped
        p = Poll.objects.create(
            question="Will this be deleted?", pub_date=datetime.now()
        )
        h = p.history.first()
        h.history_date -= timedelta(hours=1)
        h.save()

        self.assertEqual(Poll.history.all().count(), 3)
        out = StringIO()
        management.call_command(
            self.command_name,
            auto=True,
            minutes=50,
            dry=True,
            stdout=out,
            stderr=StringIO(),
        )
        self.assertEqual(
            out.getvalue(),
            "Removed 1 historical records for "
            "<class 'simple_history.tests.models.Poll'>\n",
        )
        self.assertEqual(Poll.history.all().count(), 3)
开发者ID:treyhunner,项目名称:django-simple-history,代码行数:32,代码来源:test_commands.py


示例12: test_write_ini_with_custom_converters

        def test_write_ini_with_custom_converters(self):

            def dict_encoder(dict_):
                return ','.join('%s:%s' % (k, v) for (k, v) in dict_.items())

            def dict_decoder(string):
                return dict(x.split(':') for x in string.split(','))

            n = Namespace(doc='top')
            n.add_option(
                'a',
                default={'one': 'One'},
                doc='the doc string',
                to_string_converter=dict_encoder,
                from_string_converter=dict_decoder,
            )
            c = ConfigurationManager(
                [n],
                use_admin_controls=True,
                use_auto_help=False,
                argv_source=[]
            )
            expected = "# the doc string\n#a=one:One\n"
            out = StringIO()
            c.write_conf(for_configobj, opener=stringIO_context_wrapper(out))
            received = out.getvalue()
            out.close()

            self.assertEqual(expected.strip(), received.strip())
开发者ID:mozilla,项目名称:configman,代码行数:29,代码来源:test_val_for_configobj.py


示例13: test_logging_setup_with_config_obj

    def test_logging_setup_with_config_obj(self):
        class RootController(object):
            @expose()
            def index(self):
                import logging

                logging.getLogger("pecantesting").info("HELLO WORLD")
                return "HELLO WORLD"

        f = StringIO()

        from pecan.configuration import conf_from_dict

        app = TestApp(
            make_app(
                RootController(),
                logging=conf_from_dict(
                    {
                        "loggers": {"pecantesting": {"level": "INFO", "handlers": ["memory"]}},
                        "handlers": {"memory": {"level": "INFO", "class": "logging.StreamHandler", "stream": f}},
                    }
                ),
            )
        )

        app.get("/")
        assert f.getvalue() == "HELLO WORLD\n"
开发者ID:rackerlabs,项目名称:pecan,代码行数:27,代码来源:test_base.py


示例14: run_driver

def run_driver(prob):
    """
    Call `run_driver` on problem and capture output.

    Parameters
    ----------
    prob : Problem
        an instance of Problem

    Returns
    -------
    boolean
        Failure flag; True if failed to converge, False is successful.
    string
        output from calling `run_driver` on the Problem, captured from stdout
    """
    stdout = sys.stdout
    strout = StringIO()

    sys.stdout = strout
    try:
        failed = prob.run_driver()
    finally:
        sys.stdout = stdout

    return failed, strout.getvalue()
开发者ID:OpenMDAO,项目名称:OpenMDAO,代码行数:26,代码来源:general_utils.py


示例15: test_stdlib_methods_support

 def test_stdlib_methods_support(self, method):
     """
     PrintLogger implements methods of stdlib loggers.
     """
     sio = StringIO()
     getattr(PrintLogger(sio), method)('hello')
     assert 'hello' in sio.getvalue()
开发者ID:JTCunning,项目名称:structlog,代码行数:7,代码来源:test_loggers.py


示例16: csv_users

def csv_users(request, course, lesson):
    """Exports the stats for all students on the given lesson"""
    course = get_object_or_404(Course, slug=course)
    lesson = get_object_or_404(Lesson, slug=lesson, course=course)
    
    buffer = StringIO()
    writer = csv.writer(buffer)
    
    # Headers
    writer.writerow(
        ["Username", "Attempts", "Correct", "Revealed"]
    )
    
    users = course.users.all()
    
    for u in users:
        writer.writerow([
            u.username,
            utils.attempts(user=u, task__section__lesson=lesson),
            utils.correct(user=u, task__section__lesson=lesson),
            utils.revealed(user=u, task__section__lesson=lesson),
        ])
    
    
    return HttpResponse(buffer.getvalue(), "text/csv")
开发者ID:RossBrunton,项目名称:RThing,代码行数:25,代码来源:views.py


示例17: get_input

    def get_input(self, filepath, buffer):
        """Parse received input options. If buffer is not false (=='f') if
        gets input data from input buffer othewise opens file specified in
        sourcefilename,

        Args:
            filepath (str): path to the file to read from to retrieve data
            buffer (str): if == 't' reads data from input buffer

        Returns:
            string read from filepath/buffer
        """

        if buffer != 'f':
            filepath = StringIO(sys.stdin.read())
        elif filepath is None:
            msg = "No Input! Please specify --source_filename or --buffer t"
            raise IOError(msg)
        else:
            if filepath.lower().startswith('http'):
                # Create a request for the given URL.
                request = urllib2.Request(filepath)
                data = get_data_from_url(request)
                self.last_byte = len(data)

            else:
                filepath = open(filepath, 'r').read()
                self.last_byte = len(filepath)
                filepath = StringIO(filepath)

        source = pd.read_csv(filepath)
        return source
开发者ID:,项目名称:,代码行数:32,代码来源:


示例18: test_destination_directory_levels_deep

    def test_destination_directory_levels_deep(self):
        from pecan.scaffolds import copy_dir
        f = StringIO()
        copy_dir(
            (
                'pecan', os.path.join('tests', 'scaffold_fixtures', 'simple')
            ),
            os.path.join(self.scaffold_destination, 'some', 'app'),
            {},
            out_=f
        )

        assert os.path.isfile(os.path.join(
            self.scaffold_destination, 'some', 'app', 'foo')
        )
        assert os.path.isfile(os.path.join(
            self.scaffold_destination, 'some', 'app', 'bar', 'spam.txt')
        )
        with open(os.path.join(
            self.scaffold_destination, 'some', 'app', 'foo'
        ), 'r') as f:
            assert f.read().strip() == 'YAR'
        with open(os.path.join(
            self.scaffold_destination, 'some', 'app', 'bar', 'spam.txt'
        ), 'r') as f:
            assert f.read().strip() == 'Pecan'
开发者ID:adamchainz,项目名称:pecan,代码行数:26,代码来源:test_scaffolds.py


示例19: test_write_json

    def test_write_json(self):
        n = Namespace(doc='top')
        n.add_option(
            'aaa',
            '2011-05-04T15:10:00',
            'the a',
            short_form='a',
            from_string_converter=datetime_from_ISO_string
        )

        c = ConfigurationManager(
            [n],
            use_admin_controls=True,
            use_auto_help=False,
            argv_source=[]
        )

        out = StringIO()
        c.write_conf(for_json, opener=stringIO_context_wrapper(out))
        received = out.getvalue()
        out.close()
        jrec = json.loads(received)

        expect_to_find = {
            "short_form": "a",
            "default": "2011-05-04T15:10:00",
            "doc": "the a",
            "value": "2011-05-04T15:10:00",
            "from_string_converter":
            "configman.datetime_util.datetime_from_ISO_string",
            "name": "aaa"
        }
        for key, value in expect_to_find.items():
            self.assertEqual(jrec['aaa'][key], value)
开发者ID:mozilla,项目名称:configman,代码行数:34,代码来源:test_val_for_json.py


示例20: test_writesOnlyMessageWithLF

    def test_writesOnlyMessageWithLF(self):
        sio = StringIO()
        PlainFileLogObserver(sio)(
            {"system": "some system", "message": ("hello",)}
        )

        assert "hello\n" == sio.getvalue()
开发者ID:hynek,项目名称:structlog,代码行数:7,代码来源:test_twisted.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python BaseHTTPServer.HTTPServer类代码示例发布时间:2022-05-27
下一篇:
Python moves.StringIO类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap