本文整理汇总了Python中io.StringIO方法的典型用法代码示例。如果您正苦于以下问题:Python io.StringIO方法的具体用法?Python io.StringIO怎么用?Python io.StringIO使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类io
的用法示例。
在下文中一共展示了io.StringIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format_source_or_operation
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def format_source_or_operation(self, name, group, what):
op = what.discover(self.plugins.get(group, name))
buffer = io.StringIO()
descr = op.long_descr or op.descr
if descr:
print(descr, file=buffer)
else:
print(name, file=buffer)
print("", file=buffer)
options = op.options
if options:
print("Options:", file=buffer)
for opt in options:
print("", file=buffer)
tp_descr = opt.human_type()
if tp_descr:
print(f"{opt.name}: {tp_descr}", file=buffer)
else:
print(f"{opt.name}", file=buffer)
if opt.descr:
print(format_info_text(opt.descr, indent=2), file=buffer)
return buffer.getvalue().strip()
示例2: stats
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def stats(self, filename, sortby='cumulative'):
""":rtype stats(index): output of print_stats() for the given profile.
"""
sio = io.StringIO()
if sys.version_info >= (2, 5):
s = pstats.Stats(os.path.join(self.path, filename), stream=sio)
s.strip_dirs()
s.sort_stats(sortby)
s.print_stats()
else:
# pstats.Stats before Python 2.5 didn't take a 'stream' arg,
# but just printed to stdout. So re-route stdout.
s = pstats.Stats(os.path.join(self.path, filename))
s.strip_dirs()
s.sort_stats(sortby)
oldout = sys.stdout
try:
sys.stdout = sio
s.print_stats()
finally:
sys.stdout = oldout
response = sio.getvalue()
sio.close()
return response
示例3: reset_db
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def reset_db():
"""
Reset database to a blank state by removing all the tables and recreating them.
"""
with connection.cursor() as cursor:
cursor.execute("select tablename from pg_tables where schemaname = 'public'")
tables = [row[0] for row in cursor.fetchall()]
# Can't use query parameters here as they'll add single quotes which are not
# supported by postgres
for table in tables:
cursor.execute('drop table "' + table + '" cascade')
# Call migrate so that post-migrate hooks such as generating a default Site object
# are run
management.call_command("migrate", "--noinput", stdout=StringIO())
示例4: set_setting
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def set_setting(self, name, value=None, force: bool = True):
"""
Set a setting in the environment directory, for use by Django
"""
envfile_path = os.path.join(self.envdir_path, name)
will_write = force
if not force:
try:
# Test that it does exist
self.run_in_project_root("test -r {}".format(envfile_path), hide=True)
except UnexpectedExit:
will_write = True
if will_write:
if value is None:
value = input("Value for {}: ".format(name))
# Convert booleans into values understood as such by Django
if isinstance(value, bool):
value = "1" if value else ""
self.put(StringIO("{}\n".format(value)), envfile_path)
示例5: launch
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def launch(args,q_in,q_out):
while True:
jobid,txt=q_in.get()
if jobid=="FINAL":
q_out.put((jobid,txt))
return
cache=io.StringIO()
for line in txt.split("\n"):
line=line.strip()
if not line:
continue
if line.startswith("###C:"):
print(line,file=cache)
else:
words=line.split()
for idx,w in enumerate(words):
print(idx+1,w,*(["_"]*8),sep="\t",file=cache)
print(file=cache)
q_out.put((jobid,cache.getvalue()))
示例6: launch
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def launch(args,q_in,q_out):
while True:
jobid,txt=q_in.get()
if jobid=="FINAL":
q_out.put((jobid,txt))
return
cache=io.StringIO()
for sent,comments in read_conll(txt.split("\n"),drop_tokens=False,drop_nulls=False):
if comments:
print("\n".join(comments),file=cache)
for cols in sent:
for col in (LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS):
cols[col]="_"
print("\t".join(cols),file=cache)
print(file=cache)
q_out.put((jobid,cache.getvalue()))
示例7: launch
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def launch(args,q_in,q_out):
while True:
jobid,txt=q_in.get()
if jobid=="FINAL":
q_out.put((jobid,txt))
return
cache=io.StringIO()
for sent,comments in read_conll(txt.split("\n"),drop_tokens=False,drop_nulls=False):
if len(sent)>args.max_sent_len:
comments.append("###TRIMMED_BY_PARSER FROM ORIGINAL OF {} WORDS".format(len(sent)))
sent=sent[:args.max_sent_len]
for i,token in enumerate(sent):
if len(token[FORM])>args.max_token_len:
comments.append("###TOKEN {tid} TRIMMED_BY_PARSER FROM ORIGINAL OF {l} CHARACTERS | ORIG_TOKEN={orig}".format(tid=str(i+1), l=len(token[FORM]), orig=token[FORM]))
sent[i][FORM]=token[FORM][:args.max_token_len]
if comments:
print("\n".join(comments),file=cache)
for cols in sent:
for col in (LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS):
cols[col]="_"
print("\t".join(cols),file=cache)
print(file=cache)
q_out.put((jobid,cache.getvalue()))
示例8: launch
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def launch(args,q_in,q_out):
counter=0
while True:
jobid,txt=q_in.get()
if jobid=="FINAL":
q_out.put((jobid,txt))
return
cache=io.StringIO()
for sent in sentences(txt):
print("# sent_id =",counter,file=cache)
counter+=1
#print("# text =",sent.replace("\n"," "),file=cache)
for id,token in enumerate(tokens(sent)):
print(id+1,token,*(["_"]*8),sep="\t",file=cache)
print(file=cache)
q_out.put((jobid,cache.getvalue()))
示例9: __str__
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def __str__(self):
"""Returns human readable representation, which is useful for debugging."""
buf = StringIO()
for batch_idx, (batch_id, batch_val) in enumerate(iteritems(self.data)):
if batch_idx >= TO_STR_MAX_BATCHES:
buf.write(u'...\n')
break
buf.write(u'BATCH "{0}"\n'.format(batch_id))
for k, v in iteritems(batch_val):
if k != 'images':
buf.write(u' {0}: {1}\n'.format(k, v))
for img_idx, img_id in enumerate(iterkeys(batch_val['images'])):
if img_idx >= TO_STR_MAX_IMAGES_PER_BATCH:
buf.write(u' ...')
break
buf.write(u' IMAGE "{0}" -- {1}\n'.format(img_id,
batch_val['images'][img_id]))
buf.write(u'\n')
return buf.getvalue()
示例10: install_syslinux
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def install_syslinux(self):
try:
try:
self.install_syslinux_impl()
finally:
config.process_exist = None
self.ui_enable_controls()
except (KeyboardInterrupt, SystemExit):
raise
except:
uninstall_distro.do_uninstall_distro(
config.distro, iso_basename(config.image_path))
o = io.StringIO()
traceback.print_exc(None, o)
QtWidgets.QMessageBox.information(
self, 'install_syslinux() failed',
o.getvalue())
log("install_syslinux() failed.")
log(o.getvalue())
示例11: __init__
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def __init__(self, logfile=None, verbose=True):
"""
Wrapper for the SafeConfigParser class for easy use.
@attention: config_file argument may be file path or stream.
@param logfile: file handler or file path to a log file
@type logfile: file | FileIO | StringIO | None
@param verbose: No stdout or stderr messages. Warnings and errors will be only logged to a file, if one is given
@type verbose: bool
@return: None
@rtype: None
"""
super(ConfigParserWrapper, self).__init__(
label="ConfigParserWrapper", logfile=logfile, verbose=verbose)
self._config = ConfigParser()
self._config_file_path = None
示例12: get_denominator_csv
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def get_denominator_csv(self):
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["year", "month", "officers out on service"])
values = sorted(self.denominator_values,
key=lambda x: (x.year, x.month))
for value in values:
row = [
value.year,
value.month,
value.officers_out_on_service
]
writer.writerow(row)
return output.getvalue()
示例13: test_csv_response
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def test_csv_response(self, testapp):
# create a department and an LMPD uof incident
department = Department.create(name="LM Police Department", short_name="LMPD", load_defaults=False)
uof_check = dict(department_id=department.id, opaque_id="Check Opaque ID", occured_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), bureau="Check Bureau", division="Check Division", unit="Check Unit", platoon="Check Platoon", disposition="Check Disposition", use_of_force_reason="Check UOF Reason", officer_force_type="Check Officer Force Type", service_type="Check Service Type", arrest_made=False, arrest_charges="Check Arrest Charges", resident_injured=True, resident_hospitalized=False, resident_condition="Check Resident Condition", officer_injured=False, officer_hospitalized=False, officer_condition="Check Officer Condition", resident_identifier="Check Resident Identifier", resident_race="Check Resident Race", resident_sex="Check Resident Sex", resident_age="Check Resident Age", officer_race="Check Officer Race", officer_sex="Check Officer Sex", officer_age="Check Officer Age", officer_years_of_service="Check Officer Years Of Service", officer_identifier="Check Officer Identifier")
UseOfForceIncidentLMPD.create(**uof_check)
response = testapp.get("/department/{}/uof.csv".format(department.id))
incidents = list(csv.DictReader(io.StringIO(response.text)))
# build a variable to csv header lookup from the csv schema
csv_schema = UseOfForceIncidentLMPD.get_csv_schema()
schema_lookup = dict(zip([col[1] for col in csv_schema], [col[0] for col in csv_schema]))
assert len(incidents) == 1
for check_key in uof_check.keys():
if check_key == 'department_id':
continue
assert str(uof_check[check_key]) == incidents[0][schema_lookup[check_key]]
示例14: test_csv_filtered_by_dept
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def test_csv_filtered_by_dept(self, testapp):
# create a department
department1 = Department.create(name="IM Police Department", short_name="IMPD", load_defaults=False)
department2 = Department.create(name="B Police Department", short_name="BPD", load_defaults=False)
incidentclass1 = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department1.short_name))
incidentclass2 = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department2.short_name))
incidentclass1.create(opaque_id="123ABC", department_id=department1.id)
incidentclass2.create(opaque_id="123XYZ", department_id=department2.id)
response1 = testapp.get("/department/{}/uof.csv".format(department1.id))
response2 = testapp.get("/department/{}/uof.csv".format(department2.id))
incidents1 = list(csv.DictReader(io.StringIO(response1.text)))
incidents2 = list(csv.DictReader(io.StringIO(response2.text)))
assert len(incidents1) == 1 and len(incidents2) == 1
assert incidents1[0]['id'] == '123ABC' and incidents2[0]['id'] == '123XYZ'
示例15: get_model
# 需要导入模块: import io [as 别名]
# 或者: from io import StringIO [as 别名]
def get_model(self, mode="mujoco_py"):
"""
Returns a MjModel instance from the current xml tree.
"""
available_modes = ["mujoco_py"]
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
if mode == "mujoco_py":
from mujoco_py import load_model_from_xml
model = load_model_from_xml(string.getvalue())
return model
raise ValueError(
"Unkown model mode: {}. Available options are: {}".format(
mode, ",".join(available_modes)
)
)