本文整理汇总了Python中six.StringIO.write方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.write方法的具体用法?Python StringIO.write怎么用?Python StringIO.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.StringIO
的用法示例。
在下文中一共展示了StringIO.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_css
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def write_css(context, folder, meta_bundle):
registry = getUtility(IRegistry)
resources = []
bundles = registry.collectionOfInterface(
IBundleRegistry,
prefix='plone.bundles',
check=False
)
for bundle in bundles.values():
if bundle.merge_with == meta_bundle and bundle.csscompilation:
css = get_resource(context, bundle.csscompilation)
if not css:
continue
(path, sep, filename) = bundle.csscompilation.rpartition('/')
# Process relative urls:
# we prefix with current resource path any url not starting with
# '/' or http: or data:
css = re.sub(
r"""(url\(['"]?(?!['"]?([a-z]+:|\/)))""",
r'\1%s/' % path,
css)
resources.append(css)
fi = StringIO()
for script in resources:
fi.write(script + '\n')
folder.writeFile(meta_bundle + '.css', fi)
示例2: summarize_records
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def summarize_records(recids, of, ln, searchpattern="", searchfield="",
req=None, collections=CFG_CITESUMMARY_COLLECTIONS):
"""Write summary report for records RECIDS in the format OF in language LN.
SEARCHPATTERN and SEARCHFIELD are search query that led to RECIDS,
for instance p='Smith, Paul' and f='author'. They are used for links.
REQ is the Apache/mod_python request object.
"""
if of == 'xcs':
# this is XML cite summary
citedbylist = get_cited_by_list(recids)
return render_citation_summary_xml(citedbylist)
has_req = req is not None
if not has_req:
req = StringIO()
if of == 'hcs':
renderer = render_citation_summary
else:
renderer = render_extended_citation_summary
renderer(req,
ln,
recids,
collections,
searchpattern,
searchfield)
req.write(websearch_templates.tmpl_citesummary_footer())
if has_req:
return ''
else:
return req.getvalue()
示例3: load_dataset
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def load_dataset(infile, selection, verbose=1, **kwargs):
"""
Loads selected distribution from selected infile.
Arguments:
infile (str): Path to text input file
selection (str): Start of lines containing desired dataset
verbose (int): Level of verbose output
Returns:
dataset (DataFrame): Selected dataset
"""
from six import StringIO
import pandas
if verbose >= 1:
print("loading '{0}' from '{1}'".format(selection, infile))
s = StringIO()
with open(infile) as open_infile:
for line in open_infile:
if line.startswith(selection):
s.write(line)
s.seek(0)
dataset = pandas.read_csv(s, delim_whitespace=True, header=None,
usecols=[3,4,5,6], names=["phi", "psi", "probability",
"free energy"])
return dataset
示例4: manage_test
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def manage_test(self, query, REQUEST=None):
"""Executes the SQL in parameter 'query' and returns results"""
dbc = self() # get our connection
res = dbc.query(query)
if isinstance(res, type('')):
f = StringIO()
f.write(res)
f.seek(0)
result = RDB.File(f)
else:
result = Results(res)
if REQUEST is None:
return result # return unadulterated result objects
if result._searchable_result_columns():
r = custom_default_report(self.id, result)
else:
r = 'This statement returned no results.'
report = HTML(
'<html><body bgcolor="#ffffff" link="#000099" vlink="#555555">\n'
'<dtml-var name="manage_tabs">\n<hr>\n%s\n\n'
'<hr><h4>SQL Used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n'
'</body></html>'
% (r, query))
report = report(*(self, REQUEST), **{self.id: result})
return report
示例5: _parse_config
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def _parse_config():
"""Parse the config file, set up defaults.
"""
defaults = {'apikey': apikey,
'server': server,
'verbosity': 0,
'cachedir': os.path.expanduser('~/.openml/cache'),
'avoid_duplicate_runs': 'True'}
config_file = os.path.expanduser('~/.openml/config')
config = configparser.RawConfigParser(defaults=defaults)
if not os.path.exists(config_file):
# Create an empty config file if there was none so far
fh = open(config_file, "w")
fh.close()
logger.info("Could not find a configuration file at %s. Going to "
"create an empty file there." % config_file)
try:
# Cheat the ConfigParser module by adding a fake section header
config_file_ = StringIO()
config_file_.write("[FAKE_SECTION]\n")
with open(config_file) as fh:
for line in fh:
config_file_.write(line)
config_file_.seek(0)
config.readfp(config_file_)
except OSError as e:
logging.info("Error opening file %s: %s" %
config_file, e.message)
return config
示例6: getInnerHTML
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def getInnerHTML(self):
html = StringIO()
for tag in self.tag.contents:
html.write(str(tag))
return html.getvalue()
示例7: _build_attributes_table
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def _build_attributes_table(tag, attributes, hide_attributes=False, attribute_names=None, header_level=3):
attribute_table = StringIO()
attribute_table.write("\n\n")
if attributes and not hide_attributes:
header_prefix = '#' * header_level
attribute_table.write("\n%s Attributes\n" % header_prefix)
attribute_table.write("Attribute | Details | Required\n")
attribute_table.write("--- | --- | ---\n")
for attribute in attributes:
name = attribute.attrib["name"]
if attribute_names and name not in attribute_names:
continue
details = _doc_or_none(attribute)
if details is None:
type_el = _type_el(attribute)
assert type_el is not None, "No details or type found for %s" % name
details = _doc_or_none(type_el)
annotation_el = type_el.find("{http://www.w3.org/2001/XMLSchema}annotation")
else:
annotation_el = attribute.find("{http://www.w3.org/2001/XMLSchema}annotation")
use = attribute.attrib.get("use", "optional") == "required"
if "|" in details:
# This seems to work fine for now, but potentially can cause problems.
pass
details = details.replace("\n", " ").strip()
best_practices = _get_bp_link(annotation_el)
if best_practices:
details += """ Find the Intergalactic Utilities Commision suggested best practices for this element [here](%s).""" % best_practices
attribute_table.write("``%s`` | %s | %s\n" % (name, details, use))
return attribute_table.getvalue()
示例8: get_result
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def get_result(self):
# Got to unravel the join stack; the nesting order could be
# arbitrary, so we do a depth first search and push the join tokens
# and predicates onto a flat list, then format them
op = self.expr.op()
if isinstance(op, ops.Join):
self._walk_join_tree(op)
else:
self.join_tables.append(self._format_table(self.expr))
# TODO: Now actually format the things
buf = StringIO()
buf.write(self.join_tables[0])
for jtype, table, preds in zip(self.join_types, self.join_tables[1:],
self.join_predicates):
buf.write('\n')
buf.write(util.indent('{0} {1}'.format(jtype, table), self.indent))
if len(preds):
buf.write('\n')
fmt_preds = [self._translate(pred) for pred in preds]
conj = ' AND\n{0}'.format(' ' * 3)
fmt_preds = util.indent('ON ' + conj.join(fmt_preds),
self.indent * 2)
buf.write(fmt_preds)
return buf.getvalue()
示例9: _diff
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def _diff(self, baselinedir, outputdir, dc=None):
if dc is None:
dc = filecmp.dircmp(baselinedir, outputdir, ['.svn'])
if dc.left_only:
self.fail("Files or subdirectories missing from output: "
+str(dc.left_only))
if dc.right_only:
self.fail("Files or subdirectories missing from baseline: "
+str(dc.right_only))
for name in dc.diff_files:
fromfile = join(dc.left, name)
tofile = join(dc.right, name)
with open(fromfile, 'r') as f_from:
fromlines = f_from.readlines()
with open(tofile, 'r') as f_to:
tolines = f_to.readlines()
diff = difflib.context_diff(fromlines, tolines,
fromfile+" (baseline)",
tofile+" (output)")
out = StringIO()
out.write("Output file does not match baseline:\n")
for line in diff:
out.write(line)
self.fail(out.getvalue())
for subdir in dc.subdirs:
self._diff(join(baselinedir, subdir),
join(outputdir, subdir),
dc=dc.subdirs[subdir])
shutil.rmtree(outputdir, ignore_errors=True)
示例10: format_postamble
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def format_postamble(self):
buf = StringIO()
lines = 0
if len(self.order_by) > 0:
buf.write('ORDER BY ')
formatted = []
for expr in self.order_by:
key = expr.op()
translated = self._translate(key.expr)
if not key.ascending:
translated += ' DESC'
formatted.append(translated)
buf.write(', '.join(formatted))
lines += 1
if self.limit is not None:
if lines:
buf.write('\n')
n, offset = self.limit['n'], self.limit['offset']
buf.write('LIMIT {0}'.format(n))
if offset is not None and offset != 0:
buf.write(' OFFSET {0}'.format(offset))
lines += 1
if not lines:
return None
return buf.getvalue()
示例11: report
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def report(result, csv_file):
'''generate report from backtest output file
'''
result_df = pd.read_pickle(result)
csv_txt = StringIO()
csv_txt.write("Trades\n")
fieldnames = ['date', 'order_book_id', 'amount', 'price', "commission", "tax"]
writer = csv.DictWriter(csv_txt, fieldnames=fieldnames)
writer.writeheader()
for dt, trades in result_df.trades.iteritems():
for t in trades:
trade = dict(t.__dict__)
trade.pop("order_id")
trade["date"] = trade["date"].strftime("%Y-%m-%d %H:%M:%S")
writer.writerow(trade)
csv_txt.write("\nPositions\n")
fieldnames = ['date', 'order_book_id', 'market_value', 'quantity']
writer = csv.DictWriter(csv_txt, fieldnames=fieldnames)
writer.writeheader()
for _dt, positions in result_df.positions.iteritems():
dt = _dt.strftime("%Y-%m-%d %H:%M:%S")
for order_book_id, position in iteritems(positions):
writer.writerow({
"date": dt,
"order_book_id": order_book_id,
"market_value": position.market_value,
"quantity": position.quantity,
})
with open(csv_file, 'w') as csvfile:
csvfile.write(csv_txt.getvalue())
示例12: apply_locale
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def apply_locale(self, locale, out_fn=None):
# Adjust the locals value to the new value
newconf = StringIO()
for line in util.load_file(self.login_conf_fn).splitlines():
newconf.write(re.sub(r'^default:',
r'default:lang=%s:' % locale, line))
newconf.write("\n")
# Make a backup of login.conf.
util.copy(self.login_conf_fn, self.login_conf_fn_bak)
# And write the new login.conf.
util.write_file(self.login_conf_fn, newconf.getvalue())
try:
LOG.debug("Running cap_mkdb for %s", locale)
util.subp(['cap_mkdb', self.login_conf_fn])
except util.ProcessExecutionError:
# cap_mkdb failed, so restore the backup.
util.logexc(LOG, "Failed to apply locale %s", locale)
try:
util.copy(self.login_conf_fn_bak, self.login_conf_fn)
except IOError:
util.logexc(LOG, "Failed to restore %s backup",
self.login_conf_fn)
示例13: basic_config
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def basic_config(config_file):
from six import StringIO
import yaml
buff = StringIO()
buff.write(config_file)
buff.seek(0)
return Config.from_dict(yaml.load(buff))
示例14: _type_parser
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
class _type_parser(object):
NORMAL, IN_PAREN = 0, 1
def __init__(self, value):
self.value = value
self.state = self.NORMAL
self.buf = StringIO()
self.types = []
for c in value:
self._step(c)
self._push()
def _push(self):
val = self.buf.getvalue().strip()
if val:
self.types.append(val)
self.buf = StringIO()
def _step(self, c):
if self.state == self.NORMAL:
if c == '(':
self.state = self.IN_PAREN
elif c == ',':
self._push()
return
elif self.state == self.IN_PAREN:
if c == ')':
self.state = self.NORMAL
self.buf.write(c)
示例15: fetch_data
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import write [as 别名]
def fetch_data(self):
# create a data frame directly from the full text of
# the response from the returned file-descriptor.
data = self.fetch_url(self.url)
fd = StringIO()
if isinstance(data, str):
fd.write(data)
else:
for chunk in data:
fd.write(chunk)
self.fetch_size = fd.tell()
fd.seek(0)
try:
# see if pandas can parse csv data
frames = read_csv(fd, **self.pandas_kwargs)
frames_hash = hashlib.md5(str(fd.getvalue()).encode('utf-8'))
self.fetch_hash = frames_hash.hexdigest()
except pd.parser.CParserError:
# could not parse the data, raise exception
raise Exception('Error parsing remote CSV data.')
finally:
fd.close()
return frames