Last active
October 21, 2016 20:25
-
-
Save antfu/b05cbfde4395af808220efd74c32e4f1 to your computer and use it in GitHub Desktop.
[Python] set_win_encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
'''Fix Windows encoding problem''' | |
import os | |
import sys | |
import codecs | |
def set_win_encoding(codepage=None): | |
"""Change encoding(code page) for Windows | |
Code page Country/Region/Language | |
----------------------------------- | |
437 United States | |
850 Multilingual (Latin I) | |
852 Slavic (Latin II) | |
855 Cyrillic (Russian) | |
857 Turkish | |
860 Portuguese | |
861 Icelandic | |
863 Canadian-French | |
865 Nordic | |
866 Russian | |
869 Modern Greek | |
1252 West European Latin | |
65000 UTF-7 | |
65001 UTF-8 | |
Source: http://ss64.com/nt/chcp.html | |
""" | |
# Default code page is 65001 for UTF-8 | |
codepage = str(codepage or 65001) | |
# Ensure it's Windows | |
if os.name == 'nt': | |
# Check encodings | |
if sys.stdout.encoding != ('cp'+codepage): | |
# Change the codepage by calling system command | |
os.system('@chcp ' + codepage) | |
# Replace the stdout for new encoding | |
sys.stdout = codecs.getwriter('cp'+codepage)(sys.stdout.buffer, 'strict') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment