本文整理汇总了Python中cStringIO.StringIO方法的典型用法代码示例。如果您正苦于以下问题:Python cStringIO.StringIO方法的具体用法?Python cStringIO.StringIO怎么用?Python cStringIO.StringIO使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cStringIO
的用法示例。
在下文中一共展示了cStringIO.StringIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dumps
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def dumps(obj, protocol=None):
"""Serialize obj as a string of bytes allocated in memory
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
file = StringIO()
try:
cp = CloudPickler(file, protocol=protocol)
cp.dump(obj)
return file.getvalue()
finally:
file.close()
# including pickles unloading functions in this namespace
示例2: open_local_file
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def open_local_file(self, req):
host = req.get_host()
file = req.get_selector()
localfile = url2pathname(file)
stats = os.stat(localfile)
size = stats[stat.ST_SIZE]
modified = rfc822.formatdate(stats[stat.ST_MTIME])
mtype = mimetypes.guess_type(file)[0]
stats = os.stat(localfile)
headers = mimetools.Message(StringIO(
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
(mtype or 'text/plain', size, modified)))
if host:
host, port = splitport(host)
if not host or \
(not port and socket.gethostbyname(host) in self.get_names()):
return addinfourl(open(localfile, 'rb'),
headers, 'file:'+file)
raise URLError('file not on local host')
示例3: convert_flow
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def convert_flow(self, flow):
"""Convert the flow into XHTML and write it into the internal file."""
# first write the normal HTML into a buffer
orig_file = self._file
html_file = StringIO.StringIO()
self._file = NewlineWriteFile(html_file)
super(HiNetXHTMLVisitor, self).convert_flow(flow)
self._file = orig_file
# now convert it to XHTML
html_code = html_file.getvalue()
html_code = html_code.replace('<br>', '<br />')
html_code = html_code.replace(' ', ' ')
self._file.write(html_code)
## Helper functions ##
示例4: emit
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def emit(events, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
"""
Emit YAML parsing events into a stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
from StringIO import StringIO
stream = StringIO()
getvalue = stream.getvalue
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break)
try:
for event in events:
dumper.emit(event)
finally:
dumper.dispose()
if getvalue:
return getvalue()
示例5: _get_suite
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def _get_suite(buf, default, indent=' '):
"""This is a helper function to extract a python code suite from a StringIO
object.
This will dedent the buffer's content, split it into lines, and then re-indent
it by the amount indicated.
Args:
* buf (StringIO) - The buffer to take the content from.
* default (str) - The content to use if `buf` is empty.
* indent (str) - The string to prepend to all de-indented lines.
Returns the transformed string.
"""
value = textwrap.dedent(buf.getvalue() or default).strip('\n')
return '\n'.join(indent + l for l in value.splitlines())
示例6: capture_sys_output
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def capture_sys_output(use_fake_tty=False):
"""
Wrap a block with this, and it'll capture standard out and standard error
into handy variables:
with capture_sys_output() as (stdout, stderr):
self.cmd.run()
More info: https://stackoverflow.com/questions/18651705/
"""
capture_out, capture_err = StringIO(), StringIO()
current_out, current_err = sys.stdout, sys.stderr
current_in = sys.stdin
try:
if use_fake_tty:
sys.stdin = FakeTTY(current_in)
sys.stdout, sys.stderr = capture_out, capture_err
yield capture_out, capture_err
finally:
sys.stdout, sys.stderr = current_out, current_err
sys.stdin = current_in
示例7: _run_python_script
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def _run_python_script(self, script):
"""
execute python one-liner script and return its output
:param script: string containing python script to be executed
:return: output of the python script execution, or None, if script has failed
"""
output = StringIO()
command = '"%s" -c "%s"' % (self._python_executable, script)
self.output.info('running %s' % command)
try:
self.run(command=command, output=output)
except ConanException:
self.output.info("(failed)")
return None
output = output.getvalue().strip()
self.output.info(output)
return output if output != "None" else None
示例8: make_input_stream
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def make_input_stream(input, charset):
# Is already an input stream.
if hasattr(input, 'read'):
if PY2:
return input
rv = _find_binary_reader(input)
if rv is not None:
return rv
raise TypeError('Could not find binary reader for input stream.')
if input is None:
input = b''
elif not isinstance(input, bytes):
input = input.encode(charset)
if PY2:
return StringIO(input)
return io.BytesIO(input)
示例9: setUp
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def setUp(self):
self.verbose = False
# we will then turn it back on for unittest output
saved_stdout = sys.stdout
if not self.verbose:
sys.stdout = cStringIO.StringIO()
os.chdir('../src')
os.system("./waveconverter.py -p 4 -b ../input_files/weather_s100k.bb > ../test/tmp/tmp_output.txt")
os.chdir('../test')
# now read back the info contained in the temp file
self.outputString = open("./tmp/tmp_output.txt", 'r').read()
# turn stdout back on
if not self.verbose:
sys.stdout = saved_stdout
pass
# grep through the output to confirm that the expected transmissions are there
示例10: test_store_and_build_forward_message_bad_mimes
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def test_store_and_build_forward_message_bad_mimes(self):
"""Test upload with no headers provided."""
for unused_mime in range(len(BAD_MIMES)):
# Should not require actual time value upon failure.
self.now()
self.mox.ReplayAll()
for mime_type in BAD_MIMES:
form = FakeForm({'field1': FakeForm(name='field1',
file=StringIO.StringIO('file1'),
type=mime_type,
type_options={},
filename='file',
headers={}),
})
self.assertRaisesRegexp(
webob.exc.HTTPClientError,
'Incorrectly formatted MIME type: %s' % mime_type,
self.handler.store_and_build_forward_message,
form,
'================1234==')
self.mox.VerifyAll()
示例11: test_filename_too_large
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def test_filename_too_large(self):
"""Test that exception is raised if the filename is too large."""
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40))
self.mox.ReplayAll()
filename = 'a' * blob_upload._MAX_STRING_NAME_LENGTH + '.txt'
form = FakeForm({
'field1': FakeForm(name='field1',
file=StringIO.StringIO('a'),
type='image/png',
type_options={'a': 'b', 'x': 'y'},
filename=filename,
headers={}),
})
self.assertRaisesRegexp(
webob.exc.HTTPClientError,
'The filename exceeds the maximum allowed length of 500.',
self.handler.store_and_build_forward_message,
form, '================1234==')
self.mox.VerifyAll()
示例12: test_content_type_too_large
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def test_content_type_too_large(self):
"""Test that exception is raised if the content-type is too large."""
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40))
self.mox.ReplayAll()
content_type = 'text/' + 'a' * blob_upload._MAX_STRING_NAME_LENGTH
form = FakeForm({
'field1': FakeForm(name='field1',
file=StringIO.StringIO('a'),
type=content_type,
type_options={'a': 'b', 'x': 'y'},
filename='foobar.txt',
headers={}),
})
self.assertRaisesRegexp(
webob.exc.HTTPClientError,
'The Content-Type exceeds the maximum allowed length of 500.',
self.handler.store_and_build_forward_message,
form, '================1234==')
self.mox.VerifyAll()
示例13: create_blob
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def create_blob(self):
"""Create a blob in the datastore and on disk.
Returns:
BlobKey of new blob.
"""
contents = 'a blob'
blob_key = blobstore.BlobKey('blob-key-1')
self.blob_storage.StoreBlob(blob_key, cStringIO.StringIO(contents))
entity = datastore.Entity(blobstore.BLOB_INFO_KIND,
name=str(blob_key),
namespace='')
entity['content_type'] = 'image/png'
entity['creation'] = datetime.datetime(1999, 10, 10, 8, 42, 0)
entity['filename'] = 'largeblob.png'
entity['size'] = len(contents)
datastore.Put(entity)
return blob_key
示例14: EndRedirect
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def EndRedirect(self, dispatched_output, original_output):
"""Handle the end of upload complete notification.
Makes sure the application upload handler returned an appropriate status
code.
"""
response = dev_appserver.RewriteResponse(dispatched_output)
logging.info('Upload handler returned %d', response.status_code)
outfile = cStringIO.StringIO()
outfile.write('Status: %s\n' % response.status_code)
if response.body and len(response.body.read()) > 0:
response.body.seek(0)
outfile.write(response.body.read())
else:
outfile.write(''.join(response.headers.headers))
outfile.seek(0)
dev_appserver.URLDispatcher.EndRedirect(self,
outfile,
original_output)
示例15: EndRedirect
# 需要导入模块: import cStringIO [as 别名]
# 或者: from cStringIO import StringIO [as 别名]
def EndRedirect(self, dispatched_output, original_output):
"""Process the end of an internal redirect.
This method is called after all subsequent dispatch requests have finished.
By default the output from the dispatched process is copied to the original.
This will not be called on dispatchers that do not return an internal
redirect.
Args:
dispatched_output: StringIO buffer containing the results from the
dispatched
original_output: The original output file.
Returns:
None if request handling is complete.
A new AppServerRequest instance if internal redirect is required.
"""
original_output.write(dispatched_output.read())