Modify Sys Stdout Encoding and Import From Module Conaints Dot

已发布 2019-05-10 23:23:32

Modify sys.stdout’s encoding at runtime in ‘file a.b.c.py:

def patch_stdout_utf8():
    import io, sys
    default_out = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)
    sys.stdout = default_out

Import this function in another module another.py:

def imp_module_with_dot(path, module_name):
    import imp
    with open(path, 'rb') as fp:
        return imp.load_module(
            module_name, fp, path, ('.py', 'rb', imp.PY_SOURCE)
        )

lib = imp_module_with_dot('exchange_rates.1m.py', 'exchange_rates')
lib.patch_stdout_utf8()
print(print)

will output:

$ python another.py
<function print at 0x110188d08>

instead of:

Python 3.6.7 (default, May  1 2019, 00:32:57)
>>> print(print)
<built-in function print>
comments powered by Disqus