

Python UTF-8 print fails when redirecting stdout
source link: https://blog.mathieu-leplatre.info/python-utf-8-print-fails-when-redirecting-stdout.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python UTF-8 print fails when redirecting stdout
Wed 26 January 2011Consider the following piece of code:
# -*- coding: utf-8 -*- print u"Վարդանաշեն"
Running this in a terminal works:
$ python test.py Վարդանաշեն
Redirecting standard output to a file fails:
$ python test.py > file Traceback (most recent call last): File "test.py", line 2, in <module> print u"Վարդանաշեն" UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)
Explanations are available on Python official wiki: default encoding has to be forced.
With an environment variable:
$ PYTHONIOENCODING='utf_8' $ export PYTHONIOENCODING $ python test.py > file $
With source modification:
import sys import codecs import locale sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
#python, #encoding, #shell - Posted in the Dev category
© Copyright 2020 by Mathieu Leplatre. mnmlist Theme
Content licensed under the Creative Commons attribution-noncommercial-sharealike License.
Recommend
-
28
README.md graftcp
-
177
How do you when it is finally time to make the change in something on your website and you can no more postpone it? Well, when Google starts penalising. I kept on postponing setting up https for my website
-
25
Permalink Join GitHub today GitH...
-
18
Redirecting godoc.org requests to pkg.go.dev Julie Qiu 15 December 2020 With the introduction of Go modules and the g...
-
10
Redirecting HTTP to HTTPS with AWS and ELB Feb 3, 2017 A Tale of Four Redirects Every technologist worth his or her salt has an internal list of "most hated technologies". These are the things that no...
-
29
Introduction Among the popular operating systems, they have all standardized on using standard input, standard output, and standard error with file desciptors 0, 1, and 2 respectively. This allows you to pipe the inputs and outputs...
-
19
Introduction When you use print() in python the output goes to standard output or sys.stdout. You can directly call sys.stdout.write() instead of using print(), but you can also co...
-
27
Introduction Operating systems recognize a couple special file descriptor IDs: STDIN - 0 - Input usally coming in from keyboard. STDOUT - 1 - Output from the...
-
20
在 Python 里设置 stdout 的编码 本文来自依云's Blog,转载请注明。
-
7
nohup: redirecting stderr to stdout解决办法
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK