本文整理汇总了Python中six.moves.cStringIO函数的典型用法代码示例。如果您正苦于以下问题:Python cStringIO函数的具体用法?Python cStringIO怎么用?Python cStringIO使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cStringIO函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: begin_class
def begin_class(self, classname, extends, doc, abstract):
cls = self.interface_name(classname)
self.current_class = cls
self.current_class_is_abstract = abstract
self.current_loader = cStringIO()
self.current_fields = cStringIO()
with open(os.path.join(self.outdir, "%s.java" % cls), "w") as f:
if extends:
ext = "extends " + ", ".join(self.interface_name(e) for e in extends)
else:
ext = ""
f.write("""package {package};
public interface {cls} {ext} {{
""".
format(package=self.package,
cls=cls,
ext=ext))
if self.current_class_is_abstract:
return
with open(os.path.join(self.outdir, "%sImpl.java" % cls), "w") as f:
f.write("""package {package};
public class {cls}Impl implements {cls} {{
""".
format(package=self.package,
cls=cls,
ext=ext))
self.current_loader.write("""
void Load() {
""")
示例2: test_get_strict_formula
def test_get_strict_formula(self):
smtlib_single = """
(set-logic UF_LIRA)
(declare-fun x () Bool)
(declare-fun y () Bool)
(declare-fun r () Real)
(assert (> r 0.0))
(assert x)
(check-sat)
"""
smtlib_double = smtlib_single + """
(assert (not y))
(check-sat)
"""
r = Symbol("r", REAL)
x, y = Symbol("x"), Symbol("y")
target_one = And(GT(r, Real(0)), x)
target_two = And(GT(r, Real(0)), x, Not(y))
stream_in = cStringIO(smtlib_single)
f = get_formula(stream_in)
self.assertEqual(f, target_one)
stream_in = cStringIO(smtlib_double)
f = get_formula(stream_in)
self.assertEqual(f, target_two)
stream_in = cStringIO(smtlib_double)
with self.assertRaises(PysmtValueError):
f = get_formula_strict(stream_in)
示例3: debuginfo_parser
def debuginfo_parser(adebug_package, filename):
"""
return the contents of filename
"""
try:
# dfd = open(adebug_package, "rb")
da = libarchive.Archive(adebug_package)
# da = libarchive.Archive(dfd)
for entry in da:
size = entry.size
# skip 0 byte files only, size can be 0 due to compression also!
if size == 0:
continue
# skip directories
if stat.S_ISDIR(entry.mode):
continue
# .dwz stuff is special
if filename == "dwz" and entry.pathname.startswith("./usr/lib/debug/.dwz/"):
data = da.read(entry.size)
return cStringIO(data)
elif entry.pathname.endswith(filename):
data = da.read(entry.size)
return cStringIO(data)
except Exception, exc:
print(adebug_package, str(exc))
traceback.print_exc()
示例4: test_dumped_logic
def test_dumped_logic(self):
# Dumped logic matches the logic in the example
fs = get_example_formulae()
for (f_out, _, _, logic) in fs:
buf_out = cStringIO()
script_out = smtlibscript_from_formula(f_out)
script_out.serialize(outstream=buf_out)
buf_in = cStringIO(buf_out.getvalue())
parser = SmtLibParser()
script_in = parser.get_script(buf_in)
for cmd in script_in:
if cmd.name == "set-logic":
logic_in = cmd.args[0]
if logic == logics.QF_BOOL:
self.assertEqual(logic_in, logics.QF_UF)
elif logic == logics.BOOL:
self.assertEqual(logic_in, logics.LRA)
else:
self.assertEqual(logic_in, logic, script_in)
break
else: # Loops exited normally
print("-"*40)
print(script_in)
示例5: test_run_sysargv
def test_run_sysargv(self):
bmodules = sys.modules
bargv = sys.argv
bpath = sys.path
bget_executable = runner.get_executable
try:
sys.modules = {
'__main__':
MockModule('/path/to/cwd/afile.py', '__main__', '')
}
sys.argv = ['afile.py', '...']
sys.path = ['', sys.path[1]]
runner.get_executable = get_executable
def func(arg=1):
raise NotImplementedError
out = cStringIO()
err = cStringIO()
runner.run(func, exit=False, out=out, err=err)
self.assertFalse(out.getvalue())
self.assertEqual(err.getvalue(),
"python -m afile: Bad value for arg: '...'\n"
"Usage: python -m afile [arg]\n")
finally:
sys.modules = bmodules
sys.argv = bargv
sys.path = bpath
runner.get_executable = bget_executable
示例6: test_iprint
def test_iprint(self):
top = Problem()
top.root = SellarStateConnection()
top.setup(check=False)
base_stdout = sys.stdout
try:
ostream = cStringIO()
sys.stdout = ostream
top.run()
finally:
sys.stdout = base_stdout
printed = ostream.getvalue()
self.assertEqual(printed, '')
# Turn on all iprints
top.print_all_convergence()
try:
ostream = cStringIO()
sys.stdout = ostream
top.run()
finally:
sys.stdout = base_stdout
printed = ostream.getvalue()
self.assertEqual(printed.count('NEWTON'), 3)
self.assertEqual(printed.count('GMRES'), 4)
self.assertTrue('[root] NL: NEWTON 0 | ' in printed)
self.assertTrue(' [root.sub] LN: GMRES 0 | ' in printed)
示例7: test_from_formula
def test_from_formula(self):
x, y = Symbol("x"), Symbol("y")
f = And(x, Or(y, x))
script = smtlibscript_from_formula(f)
self.assertIsNotNone(script)
outstream = cStringIO()
script.serialize(outstream)
output = outstream.getvalue()
self.assertIn("(set-logic ", output)
self.assertIn("(declare-fun x () Bool)", output)
self.assertIn("(declare-fun y () Bool)", output)
self.assertIn("(check-sat)", output)
# Use custom logic (as str)
script2 = smtlibscript_from_formula(f, logic="BOOL")
outstream = cStringIO()
script2.serialize(outstream)
output = outstream.getvalue()
self.assertIn("(set-logic BOOL)", output)
# Use custom logic (as Logic obj)
script3 = smtlibscript_from_formula(f, logic=QF_UFLIRA)
outstream = cStringIO()
script3.serialize(outstream)
output = outstream.getvalue()
self.assertIn("(set-logic QF_UFLIRA)", output)
# Custom logic must be a Logic or Str
with self.assertRaises(UndefinedLogicError):
smtlibscript_from_formula(f, logic=4)
示例8: test_capture
def test_capture():
from syn.base_utils import capture, assign
from six.moves import cStringIO
oout = cStringIO()
oerr = cStringIO()
with assign(sys, 'stdout', oout):
with assign(sys, 'stderr', oerr):
print("Outside")
sys.stderr.write('Err1\n')
with capture() as (out, err):
print("Inside")
sys.stderr.write('Err!\n')
assert out.getvalue() == 'Inside\n'
assert err.getvalue() == 'Err!\n'
print("Outside2")
sys.stderr.write('Err2\n')
assert out.getvalue() == 'Inside\n'
assert err.getvalue() == 'Err!\n'
print("Outside")
assert oout.getvalue() == 'Outside\nOutside2\n'
assert oerr.getvalue() == 'Err1\nErr2\n'
示例9: myexec
def myexec(self, s, with_exec=True):
if with_exec and not s.startswith("exec"):
s = "exec " + s
if not s.endswith("\n"): s += "\n"
# http://stackoverflow.com/questions/5342402/can-i-get-the-exit-code-of-a-command-executed-in-a-subshell-via-ssh
self.sendall(s)
#stdout = self.makefile()
#stderr = self.makefile_stderr()
# Wait for it.....
#count = 0
#while not self.recv_ready():
# time.sleep(1)
# count += 1
# if count >= 6:
# print('time out') #TODO: add exeption here
#time.sleep(10)
#return_code = self.recv_exit_status()
#print(return_code)
#result = ""
#while self.recv_ready():
##while self.recv_ready() and not self.exit_status_ready():
# o = self.recv(1024)
# #if not len(o): break
# #if o:
# print("o", o)
# result += o
#self.settimeout(30)
stdout, stderr = cStringIO(), cStringIO()
#try: #TODO: add exeption here
# Need to read the entire buffer to caputure output
while not self.exit_status_ready():
if self.recv_ready():
out_buff = self.recv(1024)
while out_buff:
#print("Indside stdout", out_buff)
stdout.write(out_buff)
out_buff = self.recv(1024)
if self.recv_stderr_ready():
error_buff = self.recv_stderr(1024)
while error_buff:
#print("Indside stderr", error_buff)
stderr.write(error_buff)
error_buff = self.recv_stderr(1024)
#except socket.timeout:
# raise socket.timeout
stdout.seek(0), stderr.seek(0)
return SSHResult(stdout, stderr, return_code=self.recv_exit_status())
示例10: write_main
def write_main(argv):
"""
write FILENAME
Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
"""
if len(argv) != 1:
print("Please provide the name of a file to write.")
return 1
filename = argv[0]
resource_name = "files/" + filename
tweaks_name = amend_filename(filename, "_tweaks")
if not pkg_resources.resource_exists("edx_lint", resource_name):
print("Don't have file %r to write." % filename)
return 2
if os.path.exists(filename):
print("Checking existing copy of %s" % filename)
tef = TamperEvidentFile(filename)
if not tef.validate():
bak_name = amend_filename(filename, "_backup")
print("Your copy of %s seems to have been edited, renaming it to %s" % (filename, bak_name))
if os.path.exists(bak_name):
print("A previous %s exists, deleting it" % bak_name)
os.remove(bak_name)
os.rename(filename, bak_name)
print("Reading edx_lint/files/%s" % filename)
cfg = configparser.RawConfigParser()
resource_string = pkg_resources.resource_string("edx_lint", resource_name).decode("utf8")
# pkg_resources always reads binary data (in both python2 and python3).
# ConfigParser.read_string only exists in python3, so we have to wrap the string
# from pkg_resources in a cStringIO so that we can pass it into ConfigParser.readfp.
cfg.readfp(cStringIO(resource_string), resource_name) # pylint: disable=deprecated-method
if os.path.exists(tweaks_name):
print("Applying local tweaks from %s" % tweaks_name)
cfg_tweaks = configparser.RawConfigParser()
cfg_tweaks.read([tweaks_name])
merge_configs(cfg, cfg_tweaks)
print("Writing %s" % filename)
output_text = cStringIO()
output_text.write(WARNING_HEADER.format(filename=filename, tweaks_name=tweaks_name))
cfg.write(output_text)
out_tef = TamperEvidentFile(filename)
if six.PY2:
output_bytes = output_text.getvalue()
else:
output_bytes = output_text.getvalue().encode("utf8")
out_tef.write(output_bytes)
return 0
示例11: _parseINI
def _parseINI(text):
from six.moves.configparser import ConfigParser
from six.moves import cStringIO
parser = ConfigParser()
try:
parser.read_file(cStringIO(text))
except AttributeError: # Python 2
parser.readfp(cStringIO(text))
return parser
示例12: test_run_success_exit
def test_run_success_exit(self):
def func():
return "test_run_success_exit"
stdout = cStringIO()
stderr = cStringIO()
self.assert_systemexit(
None, runner.run, func, args=['test'], out=stdout, err=stderr)
self.assertFalse(stderr.getvalue())
self.assertEqual(stdout.getvalue(), 'test_run_success_exit\n')
runner.run(func, args=['test'], out=stdout, err=stderr, exit=False)
示例13: capture_stdout
def capture_stdout():
oldout, olderr = sys.stdout, sys.stderr
try:
out = [cStringIO(), cStringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout, sys.stderr = oldout, olderr
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
示例14: test_run_fail_exit
def test_run_fail_exit(self):
def func():
raise errors.ArgumentError("test_run_fail_exit")
stdout = cStringIO()
stderr = cStringIO()
self.assert_systemexit(
2, runner.run, func, args=['test'], out=stdout, err=stderr)
self.assertFalse(stdout.getvalue())
self.assertTrue(stderr.getvalue())
runner.run(func, args=['test'], out=stdout, err=stderr, exit=False)
示例15: _generate_legend_images
def _generate_legend_images(gene):
cache = gene.caches[gene.options.cache]
for layer in gene.layers.values():
if "legend_mime" in layer and "legend_extention" in layer:
if layer["type"] == "wms":
session = requests.session()
session.headers.update(layer["headers"])
previous_hash = None
for zoom, resolution in enumerate(layer["grid_ref"]["resolutions"]):
legends = []
for l in layer["layers"]:
response = session.get(
layer["url"]
+ "?"
+ urlencode(
{
"SERVICE": "WMS",
"VERSION": "1.1.1",
"REQUEST": "GetLegendGraphic",
"LAYER": l,
"FORMAT": layer["legend_mime"],
"TRANSPARENT": "TRUE" if layer["legend_mime"] == "image/png" else "FALSE",
"STYLE": layer["wmts_style"],
"SCALE": resolution / 0.00028,
}
)
)
try:
legends.append(Image.open(cStringIO(response.content)))
except: # pragma: nocover
logger.warn(
"Unable to read legend image for layer '%s', resolution '%i': %r"
% (layer["name"], resolution, response.content)
)
width = max(i.size[0] for i in legends)
height = sum(i.size[1] for i in legends)
image = Image.new("RGBA", (width, height))
y = 0
for i in legends:
image.paste(i, (0, y))
y += i.size[1]
string_io = cStringIO()
image.save(string_io, FORMAT_BY_CONTENT_TYPE[layer["legend_mime"]])
result = string_io.getvalue()
new_hash = sha1(result).hexdigest()
if new_hash != previous_hash:
previous_hash = new_hash
_send(
result,
"1.0.0/%s/%s/legend%s.%s"
% (layer["name"], layer["wmts_style"], zoom, layer["legend_extention"]),
layer["legend_mime"],
cache,
)