本文整理汇总了Python中six.moves.cStringIO类的典型用法代码示例。如果您正苦于以下问题:Python cStringIO类的具体用法?Python cStringIO怎么用?Python cStringIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了cStringIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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()
示例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)
示例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()
示例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
示例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 == ''
示例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)
示例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)
示例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()
示例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'
示例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)
示例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())
示例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"
示例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()
示例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()