From: Christian Herdtweck Date: Mon, 11 Feb 2019 09:50:13 +0000 (+0100) Subject: Auto-detect str/bytes when dumping cnf vars X-Git-Tag: v1.4~3^2~3 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=c24fd52c1a7307d08f7ab4b9c3ed438e0689968e;p=pyi2ncommon Auto-detect str/bytes when dumping cnf vars This is the second attempt to solve the problem when to "print" byte strings and when to use regular unicode strings. One problem is that sys.stdout can be a text stream or a byte stream depending on shell environment. --- diff --git a/src/cnfvar.py b/src/cnfvar.py index 551093a..cb143f9 100644 --- a/src/cnfvar.py +++ b/src/cnfvar.py @@ -711,18 +711,29 @@ def write_cnf_raw(*argv, **kw_argv): print_cnf_raw(*argv, **kw_argv) -def output_cnf(root, out, renumber=False, bytes=True): +def output_cnf(root, out, renumber=False): + """ + Dump a textual representation of given CNF VAR structure to given stream. + + Runs :py:func:`format_cnf_vars` on the input (`root`) and then writes that + to the given file-like object (out). + + :param root: a CNF_VAR structure + :type root: dict or list or anything that :py:func:`cnf_root` accepts + :param out: file-like object or something with a `write(str)` function + :param bool renumber: Whether to renumber cnfvars first + """ cnf = cnf_root(root) if renumber is True: _count = renumber_vars(root) if is_cnf(cnf) is True: (_, lines) = functools.reduce(format_cnf_vars, cnf, (0, [])) - if bytes is False: - out.write ("\n".join (map (from_latin1, lines))) - out.write ("\n") - else: + if isinstance(out, (io.RawIOBase, io.BufferedIOBase)): out.write (b"\n".join (lines)) out.write (b"\n") + else: # either subclass of io.TextIOBase or unknown + out.write ("\n".join (map (from_latin1, lines))) + out.write ("\n") def dump_cnf_bytes (root, renumber=False): @@ -732,7 +743,7 @@ def dump_cnf_bytes (root, renumber=False): """ cnf = cnf_root(root) out = io.BytesIO() - output_cnf(root, out, renumber=renumber, bytes=True) + output_cnf(root, out, renumber=renumber) res = out.getvalue() out.close() return res @@ -745,14 +756,14 @@ def dump_cnf_string(root, renumber=False): """ cnf = cnf_root(root) out = io.BytesIO() - output_cnf(root, out, renumber=renumber, bytes=False) + output_cnf(root, out, renumber=renumber) res = out.getvalue() out.close() return res def print_cnf(root, out=None, renumber=False): if root is not None: - output_cnf(root, out or sys.stdout, renumber=renumber, bytes=False) + output_cnf(root, out or sys.stdout, renumber=renumber) def write_cnf(*argv, **kw_argv):