本文整理汇总了Python中six.moves.StringIO.write方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.write方法的具体用法?Python StringIO.write怎么用?Python StringIO.write使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.StringIO
的用法示例。
在下文中一共展示了StringIO.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: smart_unquote
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def smart_unquote(s):
"""
Returns a string that is created from the input string by unquoting all
quoted regions in there. If there are no quoted regions in the input string
then output string is identical to the input string.
"""
unquoted = StringIO()
escaped_char = False
is_quoted_section = False
for c in s:
if is_quoted_section:
if escaped_char:
escaped_char = False
else:
if c == '"':
is_quoted_section = False
continue
elif c == '\\':
escaped_char = True
continue
else:
if c == '"':
is_quoted_section = True
continue
unquoted.write(c)
return unquoted.getvalue()
示例2: init_3d
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def init_3d():
"""Initialise 3D plots within the IPython notebook, by injecting the
required javascript libraries.
"""
library_javascript = StringIO()
library_javascript.write("""
<p>Loading javascript for 3D plot in browser</p>
/* Beginning of javascript injected by multinet.js */
<script type="text/javascript" src="multinet/static/js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="multinet/static/js/jquery-ui-1.11.4.js"></script>
<script type="text/javascript" src="multinet/static/js/threejs/three-r71.js"></script>
<script type="text/javascript" src="multinet/static/js/threejs/orbitcontrols.js"></script>
<script type="text/javascript" src="multinet/static/js/threejs/stats-r12.min.js"></script>
<script type="text/javascript" src="multinet/static/js/threejs/detector.js"></script>
<script type="text/javascript" src="multinet/static/js/multinet-core.js"></script>
<script type="text/javascript">
var multinet_javascript_injected = true;
</script>
""")
library_javascript.write(
"/* End of javascript injected by multinet.js */\n</script>\n")
display(HTML(library_javascript.getvalue()))
示例3: _MockLogger
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
class _MockLogger(object):
def __init__(self):
self._output = StringIO()
def message(self, msg):
self._output.write(msg.message)
def value(self):
return self._output.getvalue()
示例4: test_deqatn_6
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def test_deqatn_6(self):
func_str = 'def f(x, y, z):\n'
func_str += ' c = 3\n'
func_str += ' return x + y + z + c\n'
#func = exec(fnc_str)
s = StringIO()
s.write(s)
s.close()
exec (func_str)
f(1, 2, 3)
#func = exec func_str
assert f(1, 2, 3) == 9, func(1, 2, 3)
示例5: _report_testsuite
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def _report_testsuite(suite_name, tests, xml_document, parentElement,
properties):
"""
Appends the testsuite section to the XML document.
"""
testsuite = xml_document.createElement('testsuite')
parentElement.appendChild(testsuite)
testsuite.setAttribute('name', suite_name)
testsuite.setAttribute('tests', str(len(tests)))
testsuite.setAttribute(
'time', '%.3f' % sum(map(lambda e: e.elapsed_time, tests))
)
failures = filter(lambda e: e.outcome == e.FAILURE, tests)
testsuite.setAttribute('failures', str(len(list(failures))))
errors = filter(lambda e: e.outcome == e.ERROR, tests)
testsuite.setAttribute('errors', str(len(list(errors))))
skips = filter(lambda e: e.outcome == _TestInfo.SKIP, tests)
testsuite.setAttribute('skipped', str(len(list(skips))))
_XMLTestResult._report_testsuite_properties(
testsuite, xml_document, properties)
for test in tests:
_XMLTestResult._report_testcase(test, testsuite, xml_document)
systemout = xml_document.createElement('system-out')
testsuite.appendChild(systemout)
stdout = StringIO()
for test in tests:
# Merge the stdout from the tests in a class
if test.stdout is not None:
stdout.write(test.stdout)
_XMLTestResult._createCDATAsections(
xml_document, systemout, stdout.getvalue())
systemerr = xml_document.createElement('system-err')
testsuite.appendChild(systemerr)
stderr = StringIO()
for test in tests:
# Merge the stderr from the tests in a class
if test.stderr is not None:
stderr.write(test.stderr)
_XMLTestResult._createCDATAsections(
xml_document, systemerr, stderr.getvalue())
return testsuite
示例6: test_throw_exception_if_input_data_invalid
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def test_throw_exception_if_input_data_invalid(self):
"""4.5.5.3 Throw exception if input data is invalid."""
membuf = StringIO()
membuf.write("invalid")
membuf.seek(0)
self.patch(sys, "stdin", membuf)
if sys.version_info.major <= 2:
with ExpectedException(ValueError):
load.main()
elif sys.version_info.major >= 3:
with ExpectedException(json.decoder.JSONDecodeError):
load.main()
示例7: print_ascii_graph
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def print_ascii_graph(model_):
"""
pip install img2txt.py
python -c
"""
from PIL import Image
from six.moves import StringIO
#import networkx as netx
import copy
model = copy.deepcopy(model_)
assert model is not model_
# model.graph.setdefault('graph', {})['size'] = '".4,.4"'
model.graph.setdefault('graph', {})['size'] = '".3,.3"'
model.graph.setdefault('graph', {})['height'] = '".3,.3"'
pydot_graph = netx.to_pydot(model)
png_str = pydot_graph.create_png(prog='dot')
sio = StringIO()
sio.write(png_str)
sio.seek(0)
pil_img = Image.open(sio)
print('pil_img.size = %r' % (pil_img.size,))
#def print_ascii_image(pil_img):
# img2txt = ut.import_module_from_fpath('/home/joncrall/venv/bin/img2txt.py')
# import sys
# pixel = pil_img.load()
# width, height = pil_img.size
# bgcolor = None
# #fill_string =
# img2txt.getANSIbgstring_for_ANSIcolor(img2txt.getANSIcolor_for_rgb(bgcolor))
# fill_string = "\x1b[49m"
# fill_string += "\x1b[K" # does not move the cursor
# sys.stdout.write(fill_string)
# img_ansii_str = img2txt.generate_ANSI_from_pixels(pixel, width, height, bgcolor)
# sys.stdout.write(img_ansii_str)
def print_ascii_image(pil_img):
#https://gist.github.com/cdiener/10491632
SC = 1.0
GCF = 1.0
WCF = 1.0
img = pil_img
S = (int(round(img.size[0] * SC * WCF * 3)), int(round(img.size[1] * SC)))
img = np.sum( np.asarray( img.resize(S) ), axis=2)
print('img.shape = %r' % (img.shape,))
img -= img.min()
chars = np.asarray(list(' .,:;irsXA253hMHGS#9B&@'))
img = (1.0 - img / img.max()) ** GCF * (chars.size - 1)
print( "\n".join( ("".join(r) for r in chars[img.astype(int)]) ) )
print_ascii_image(pil_img)
pil_img.close()
pass
示例8: _find_snippet_imports
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def _find_snippet_imports(module_data, module_path, strip_comments):
"""
Given the source of the module, convert it to a Jinja2 template to insert
module code and return whether it's a new or old style module.
"""
module_style = "old"
if REPLACER in module_data:
module_style = "new"
elif REPLACER_WINDOWS in module_data:
module_style = "new"
elif "from ansible.module_utils." in module_data:
module_style = "new"
elif "WANT_JSON" in module_data:
module_style = "non_native_want_json"
output = StringIO()
lines = module_data.split("\n")
snippet_names = []
for line in lines:
if REPLACER in line:
output.write(_slurp(os.path.join(_SNIPPET_PATH, "basic.py")))
snippet_names.append("basic")
if REPLACER_WINDOWS in line:
ps_data = _slurp(os.path.join(_SNIPPET_PATH, "powershell.ps1"))
output.write(ps_data)
snippet_names.append("powershell")
elif line.startswith("from ansible.module_utils."):
tokens = line.split(".")
import_error = False
if len(tokens) != 3:
import_error = True
if " import *" not in line:
import_error = True
if import_error:
raise AnsibleError(
"error importing module in %s, expecting format like 'from ansible.module_utils.basic import *'"
% module_path
)
snippet_name = tokens[2].split()[0]
snippet_names.append(snippet_name)
output.write(_slurp(os.path.join(_SNIPPET_PATH, snippet_name + ".py")))
else:
if strip_comments and line.startswith("#") or line == "":
pass
output.write(line)
output.write("\n")
if not module_path.endswith(".ps1"):
# Unixy modules
if len(snippet_names) > 0 and not "basic" in snippet_names:
raise AnsibleError("missing required import in %s: from ansible.module_utils.basic import *" % module_path)
else:
# Windows modules
if len(snippet_names) > 0 and not "powershell" in snippet_names:
raise AnsibleError("missing required import in %s: # POWERSHELL_COMMON" % module_path)
return (output.getvalue(), module_style)
示例9: load_cookies_file
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def load_cookies_file(cookies_file):
"""
Loads the cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string.
"""
cookies = StringIO()
cookies.write('# Netscape HTTP Cookie File')
cookies.write(open(cookies_file, 'rU').read())
cookies.flush()
cookies.seek(0)
return cookies
示例10: init_3d
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def init_3d():
"""Initialise 3D plots within the IPython notebook, by injecting the
required javascript libraries.
"""
library_javascript = StringIO()
library_javascript.write("""
<script type="text/javascript">
/* Beginning of javascript injected by OpenModes */
var openmodes_javascript_injected = true;
""")
three_js_libraries = ("three.min.js", "OrbitControls.js",
"Lut.js", "Detector.js", "CanvasRenderer.js",
"Projector.js")
# Include required parts of three.js inline
for library in three_js_libraries:
with open(osp.join(three_js_dir, library)) as infile:
library_javascript.write(infile.read())
# include my custom javascript inline
with open(osp.join(static_dir, "three_js_plot.js")) as infile:
library_javascript.write(infile.read())
library_javascript.write(
"/* End of javascript injected by OpenModes */\n</script>\n")
display(HTML(library_javascript.getvalue()))
logging.info("Javascript injected for 3D interactive WebGL plots")
示例11: _filter_leading_non_json_lines
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def _filter_leading_non_json_lines(self, data):
'''
Used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter only leading lines since multiline JSON is valid.
'''
filtered_lines = StringIO()
stop_filtering = False
for line in data.splitlines():
if stop_filtering or line.startswith('{') or line.startswith('['):
stop_filtering = True
filtered_lines.write(line + '\n')
return filtered_lines.getvalue()
示例12: load_cookies_file
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def load_cookies_file(cookies_file):
"""
Loads the cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string.
"""
logging.debug("Loading cookie file %s into memory.", cookies_file)
cookies = StringIO()
cookies.write("# Netscape HTTP Cookie File")
cookies.write(open(cookies_file, "rU").read())
cookies.flush()
cookies.seek(0)
return cookies
示例13: _consume_stderr
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def _consume_stderr(self, chan, call_line_handler_func=False):
"""
Try to consume stderr data from chan if it's receive ready.
"""
out = bytearray()
stderr = StringIO()
if chan.recv_stderr_ready():
data = chan.recv_stderr(self.CHUNK_SIZE)
if six.PY3 and isinstance(data, six.text_type):
data = data.encode('utf-8')
out += data
while data:
ready = chan.recv_stderr_ready()
if not ready:
break
data = chan.recv_stderr(self.CHUNK_SIZE)
if six.PY3 and isinstance(data, six.text_type):
data = data.encode('utf-8')
out += data
stderr.write(self._get_decoded_data(out))
if self._handle_stderr_line_func and call_line_handler_func:
data = strip_shell_chars(stderr.getvalue())
lines = data.split('\n')
lines = [line for line in lines if line]
for line in lines:
# Note: If this function performs network operating no sleep is
# needed, otherwise if a long blocking operating is performed,
# sleep is recommended to yield and prevent from busy looping
self._handle_stderr_line_func(line=line + '\n')
stderr.seek(0)
return stderr
示例14: cmdline_example_to_rst
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def cmdline_example_to_rst(src, out=None, ref=None):
if out is None:
from six.moves import StringIO
out = StringIO()
# place header
out.write('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
if ref:
# place cross-ref target
out.write('.. {0}:\n\n'.format(ref))
# parser status vars
inexample = False
incodeblock = False
for line in src:
if line.startswith('#% EXAMPLE START'):
inexample = True
incodeblock = False
continue
if not inexample:
continue
if line.startswith('#% EXAMPLE END'):
break
if not inexample:
continue
if line.startswith('#%'):
incodeblock = not incodeblock
if incodeblock:
out.write('\n.. code-block:: sh\n\n')
continue
if not incodeblock and line.startswith('#'):
out.write(line[(min(2, len(line) - 1)):])
continue
if incodeblock:
if not line.rstrip().endswith('#% SKIP'):
out.write(' %s' % line)
continue
if not len(line.strip()):
continue
else:
raise RuntimeError("this should not happen")
return out
示例15: _recover_base64
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import write [as 别名]
def _recover_base64(s):
if six.PY2:
return s.translate(None, _b64_invalid_chars)
buf = StringIO()
chunk_start = 0
for i, c in enumerate(s):
if (('A' <= c <= 'Z') or
('a' <= c <= 'z') or
('0' <= c <= '9') or
c == '+' or c == '/'
):
continue
buf.write(s[chunk_start:i])
chunk_start = i + 1
buf.write(s[chunk_start:len(s)])
return buf.getvalue()