[Tutor] logging to cmd.exe

eryk sun eryksun at gmail.com
Tue Sep 26 10:48:44 EDT 2017


On Tue, Sep 26, 2017 at 7:35 AM, Mats Wichmann <mats at wichmann.us> wrote:
> On 09/26/2017 05:22 AM, Albert-Jan Roskam wrote:
>
>> Rather than change your code can you change the codepage with the chcp
>> command?
>
> the way chcp takes effect is problematic for this:
>
> "Programs that you start after you assign a new code page use the new
> code page, however, programs (except Cmd.exe) that you started before
> assigning the new code page use the original code page. "

Some console applications only check the codepage at startup. If you
change it while the program is running, they'll encode/decode text for
the original codepage, but the console will decode/encode it for its
current codepage. That's called mojibake.

Prior to 3.6, at startup Python uses the input codepage for sys.stdin,
and the output codepage for sys.stdout and sys.stderr. You can of
course rebind sys.std* if you change the codepage via chcp.com or
SetConsoleCP() and SetConsoleOutputCP(). If you do change the
codepage, it's considerate to remember the previous value and restore
it in an atexit function.

> I think there's also a module you can use for pre-3.6, sorry too lazy to
> do a search.

It's win_unicode_console [1].

[1]: https://pypi.python.org/pypi/win_unicode_console


More information about the Tutor mailing list