I'm trying to print a simple calendar from python calendar
module:
import calendar
c = calendar.LocaleTextCalendar(0, 'Russian')
s = c.formatmonth(2016, 5)
print(s)
On linux it works well, but on Windows I got an error: UnicodeEncodeError: 'charmap' codec can't encode characters in position 4-10: character maps to <undefined>
All I can do to avoid the error is print(s.encode('ascii', 'replace').decode('ascii'))
(with locale text values missed), so I'm intrested in common nice solution.
Thanks in advance.
That happens because the windows console encoding is not Unicode. Unfortunately it is not trivial and there are several way to work around this.
What is the encoding of your console? You can find out in Python this way
import sys
sys.stdin.encoding
you can try to set Unicode this way only for the current console:
chcp 65001
python myScript.py
In your script make sure that your string is encoded into UTF-8.
I solved the issue as following:
import platform
if platform.system() == 'Windows':
import locale
locale.setlocale(locale.LC_ALL, "Russian")
...
print(s) # Works!
Another option is encode/decode inside print:
print(s.encode('cp1252').decode('cp1251'))
Both cases works for file output too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.