本文整理汇总了Python中six.moves.StringIO方法的典型用法代码示例。如果您正苦于以下问题:Python moves.StringIO方法的具体用法?Python moves.StringIO怎么用?Python moves.StringIO使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves
的用法示例。
在下文中一共展示了moves.StringIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __str__
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def __str__(self):
sio = StringIO()
print(" node:", self.node, file=sio)
print(" node.inputs:", [(str(i), id(i))
for i in self.node.inputs], file=sio)
print(" node.outputs:", [(str(i), id(i))
for i in self.node.outputs], file=sio)
print(" view_map:", getattr(self.node.op, 'view_map', {}), file=sio)
print(" destroy_map:", getattr(self.node.op,
'destroy_map', {}), file=sio)
print(" aliased output:", self.output_idx, file=sio)
print(" aliased output storage:", self.out_storage, file=sio)
if self.in_alias_idx:
print(" aliased to inputs:", self.in_alias_idx, file=sio)
if self.out_alias_idx:
print(" aliased to outputs:", self.out_alias_idx, file=sio)
return sio.getvalue()
示例2: formatException
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def formatException(self, exc_info, record=None):
"""Format exception output with CONF.logging_exception_prefix."""
if not record:
return logging.Formatter.formatException(self, exc_info)
stringbuffer = moves.StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
None, stringbuffer)
lines = stringbuffer.getvalue().split('\n')
stringbuffer.close()
if CONF.logging_exception_prefix.find('%(asctime)') != -1:
record.asctime = self.formatTime(record, self.datefmt)
formatted_lines = []
for line in lines:
pl = CONF.logging_exception_prefix % record.__dict__
fl = '%s%s' % (pl, line)
formatted_lines.append(fl)
return '\n'.join(formatted_lines)
示例3: captured_output
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def captured_output(comm, root=0):
"""
Re-direct stdout and stderr to null for every rank but ``root``
"""
# keep output on root
if root is not None and comm.rank == root:
yield sys.stdout, sys.stderr
else:
from six.moves import StringIO
from nbodykit.extern.wurlitzer import sys_pipes
# redirect stdout and stderr
old_stdout, sys.stdout = sys.stdout, StringIO()
old_stderr, sys.stderr = sys.stderr, StringIO()
try:
with sys_pipes() as (out, err):
yield out, err
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
示例4: test_credentials_are_generated_from_saml
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def test_credentials_are_generated_from_saml(self, mock_sts):
mock_conn = MagicMock()
mock_conn.assume_role_with_saml.return_value = Struct({'credentials':
Struct({'expiration': 'SAML_TOKEN_EXPIRATION',
'access_key': 'SAML_ACCESS_KEY',
'secret_key': 'SAML_SECRET_KEY',
'session_token': 'SAML_TOKEN'})})
mock_sts.connect_to_region.return_value = mock_conn
sys.stdin = StringIO(saml_assertion(['arn:aws:iam::1111:role/DevRole,arn:aws:iam::1111:saml-provider/IDP']))
cli.main(['test.py', 'saml',
'--profile', 'test-profile',
'--region', 'un-south-1'])
six.assertCountEqual(self,
read_config_file(self.TEST_FILE),
['[test-profile]',
'output = json',
'region = un-south-1',
'aws_access_key_id = SAML_ACCESS_KEY',
'aws_secret_access_key = SAML_SECRET_KEY',
'aws_security_token = SAML_TOKEN',
'aws_session_token = SAML_TOKEN',
''])
示例5: test_multiple
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def test_multiple():
data = StringIO(">seq1\nACGT\n>seq2\nTGCA\n\n>seq3\nTTTT")
iterator = FastaIter(data)
header, seq = six.next(iterator)
assert header == "seq1"
assert seq == "ACGT"
header, seq = six.next(iterator)
assert header == "seq2"
assert seq == "TGCA"
header, seq = six.next(iterator)
assert header == "seq3"
assert seq == "TTTT"
# should be empty now
with pytest.raises(StopIteration):
six.next(iterator)
示例6: preview_sql
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def preview_sql(self, url, step, **args):
"""Mocks SQLAlchemy Engine to store all executed calls in a string
and runs :meth:`PythonScript.run <migrate.versioning.script.py.PythonScript.run>`
:returns: SQL file
"""
buf = StringIO()
args['engine_arg_strategy'] = 'mock'
args['engine_arg_executor'] = lambda s, p = '': buf.write(str(s) + p)
@with_engine
def go(url, step, **kw):
engine = kw.pop('engine')
self.run(engine, step)
return buf.getvalue()
return go(url, step, **args)
示例7: test_key_material_argument
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def test_key_material_argument(self):
path = os.path.join(get_resources_base_path(),
'ssh', 'dummy_rsa')
with open(path, 'r') as fp:
private_key = fp.read()
conn_params = {'hostname': 'dummy.host.org',
'username': 'ubuntu',
'key_material': private_key}
mock = ParamikoSSHClient(**conn_params)
mock.connect()
pkey = paramiko.RSAKey.from_private_key(StringIO(private_key))
expected_conn = {'username': 'ubuntu',
'allow_agent': False,
'hostname': 'dummy.host.org',
'look_for_keys': False,
'pkey': pkey,
'timeout': 60,
'port': 22}
mock.client.connect.assert_called_once_with(**expected_conn)
示例8: test_reverse_words
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def test_reverse_words():
old_limit = config.recursion_limit
config.recursion_limit = 100000
with tempfile.NamedTemporaryFile() as f_save,\
tempfile.NamedTemporaryFile() as f_data:
with open(f_data.name, 'wt') as data:
for i in range(10):
print("A line.", file=data)
main("train", f_save.name, 1, [f_data.name])
real_stdin = sys.stdin
sys.stdin = StringIO('abc\n10\n')
main("beam_search", f_save.name, 10)
sys.stdin = real_stdin
config.recursion_limit = old_limit
示例9: setUp
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def setUp(self):
super(UtilTest, self).setUp()
self.stdout = StringIO()
self.stubs = mox3_stubout.StubOutForTesting()
self.stubs.SmartSet(sys, 'stdout', self.stdout)
示例10: setUp
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def setUp(self):
super(ManagerTest, self).setUp()
# Save the real modules for clean up.
self.real_open = builtins.open
# Create a fake file system and stub out builtin modules.
self.fs = fake_filesystem.FakeFilesystem()
self.os = fake_filesystem.FakeOsModule(self.fs)
self.open = fake_filesystem.FakeFileOpen(self.fs)
self.stdout = StringIO()
self.stubs = mox3_stubout.StubOutForTesting()
self.stubs.SmartSet(builtins, 'open', self.open)
self.stubs.SmartSet(common, 'os', self.os)
self.stubs.SmartSet(sys, 'stdout', self.stdout)
# Setup Testdata.
self._testdata_path = '/testdata'
self._valid_config_path = self._testdata_path + '/valid_config.yaml'
self._blank_config_path = self._testdata_path + '/blank_config.yaml'
self.fs.CreateFile(self._valid_config_path, contents=_VALID_CONFIG)
self.fs.CreateFile(self._blank_config_path, contents=_BLANK_CONFIG)
# Load the default config.
self._valid_default_config = common.ProjectConfig.from_yaml(
common.DEFAULT, self._valid_config_path)
# Create test constants.
self._constants = {
'test': app_constants.Constant(
'test', 'message', '',
parser=utils.StringParser(allow_empty_string=False),),
'other': app_constants.Constant('other', 'other message', 'value'),
}
# Mock out the authentication credentials.
self.auth_patcher = mock.patch.object(auth, 'CloudCredentials')
self.mock_creds = self.auth_patcher.start()
self.mock_creds.return_value.get_credentials.return_value = (
credentials.AnonymousCredentials())
示例11: testDuckTyping
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def testDuckTyping(self):
# We want to support arbitrary classes that implement the stream
# interface.
class StringPassThrough(object):
def __init__(self, stream):
self.stream = stream
def read(self, *args, **kwargs):
return self.stream.read(*args, **kwargs)
dstr = StringPassThrough(StringIO('2014 January 19'))
self.assertEqual(parse(dstr), datetime(2014, 1, 19))
示例12: testParseStream
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def testParseStream(self):
dstr = StringIO('2014 January 19')
self.assertEqual(parse(dstr), datetime(2014, 1, 19))
示例13: str_diagnostic
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def str_diagnostic(self):
"""
Return a pretty multiline string representing the cause of
the exception.
"""
sio = StringIO()
print("BadThunkOutput", file=sio)
print(" Apply :", self.r.owner, file=sio)
print(" op :", self.offending_op(), file=sio)
print(" Outputs Type:", self.r.type, file=sio)
print(" Outputs Shape:", getattr(self.val1, 'shape', None), file=sio)
print(" Outputs Strides:", getattr(self.val1, 'strides', None),
file=sio)
print(" Inputs Type :", [i.type for i in self.r.owner.inputs],
file=sio)
print(" Inputs Shape:", [getattr(val, 'shape', None)
for val in self.inputs_val], file=sio)
print(" Inputs Strides:", [getattr(val, 'strides', None)
for val in self.inputs_val], file=sio)
scalar_values = []
for ipt in self.inputs_val:
if getattr(ipt, "size", -1) <= 10:
scalar_values.append(ipt)
else:
scalar_values.append("not shown")
print(" Inputs values: %s" % scalar_values, file=sio)
print(" Bad Variable:", self.r, file=sio)
print(" thunk1 :", self.thunk1, file=sio)
print(" thunk2 :", self.thunk2, file=sio)
# Don't import it at the top of the file to prevent circular import.
utt = theano.tests.unittest_tools
print(utt.str_diagnostic(self.val1, self.val2, None, None), file=sio)
ret = sio.getvalue()
return ret
示例14: instantiate_code
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def instantiate_code(self, n_args):
code = StringIO()
struct_name = self.struct_name
print("static PyObject * instantiate(PyObject * self, PyObject *argtuple) {", file=code)
print(' assert(PyTuple_Check(argtuple));', file=code)
print(' if (%(n_args)i != PyTuple_Size(argtuple)){ ' % locals(), file=code)
print(' PyErr_Format(PyExc_TypeError, "Wrong number of arguments, expected %(n_args)i, got %%i", (int)PyTuple_Size(argtuple));' % locals(), file=code)
print(' return NULL;', file=code)
print(' }', file=code)
print(' %(struct_name)s* struct_ptr = new %(struct_name)s();' % locals(), file=code)
print(' if (struct_ptr->init(', ','.join('PyTuple_GET_ITEM(argtuple, %i)' % n for n in xrange(n_args)), ') != 0) {', file=code)
print(' delete struct_ptr;', file=code)
print(' return NULL;', file=code)
print(' }', file=code)
if PY3:
print("""\
PyObject* thunk = PyCapsule_New((void*)(&{struct_name}_executor), NULL, {struct_name}_destructor);
if (thunk != NULL && PyCapsule_SetContext(thunk, struct_ptr) != 0) {{
PyErr_Clear();
Py_DECREF(thunk);
thunk = NULL;
}}
""".format(**locals()), file=code)
else:
print(' PyObject* thunk = PyCObject_FromVoidPtrAndDesc((void*)(&%(struct_name)s_executor), struct_ptr, %(struct_name)s_destructor);' % locals(), file=code)
print(" return thunk; }", file=code)
return code.getvalue()
示例15: test_record_good
# 需要导入模块: from six import moves [as 别名]
# 或者: from six.moves import StringIO [as 别名]
def test_record_good():
"""
Tests that when we record a sequence of events, then
repeat it exactly, the Record class:
1) Records it correctly
2) Does not raise any errors
"""
# Record a sequence of events
output = StringIO()
recorder = Record(file_object=output, replay=False)
num_lines = 10
for i in xrange(num_lines):
recorder.handle_line(str(i) + '\n')
# Make sure they were recorded correctly
output_value = output.getvalue()
assert output_value == ''.join(str(i) + '\n' for i in xrange(num_lines))
# Make sure that the playback functionality doesn't raise any errors
# when we repeat them
output = StringIO(output_value)
playback_checker = Record(file_object=output, replay=True)
for i in xrange(num_lines):
playback_checker.handle_line(str(i) + '\n')