UnicodeEncodeErrorと怒られる
python3.6 -c 'print("あ")'
Unable to decode the command from the command line:
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 7-9: surrogates not allowed
2通りの方法で解決できるらしい
1. pythonのスクリプト内でエンコーディングを設定する方法
python3.6 -c 'import io, sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
print("あ")'
2. pythonのスクリプト内でエンコーディングを設定する方法
echo $locale
echo $LC_ALL
export LC_ALL=en_US.UTF-8
echo $locale
echo $LC_ALL
en_US.UTF-8
python3.6 -c 'print("あ")'
あ
補足: input()等で入力する場合、 stdinのエンコードも指定しておくこと
# stdout スクリプトからの標準出力しか指定していない sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") # input()等でコマンドラインで入力させる場合、 # stdin スクリプトへの標準入力も指定してしておこう sys.stdin = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
cf. python3 ‘ascii’ codec can’t encode character ‘\u3042’ in position 0: ordinal not in range(128)解決方法
https://tokyo-engineer.com/python3_ascii_codec_cant_encode_character/
cf. (Windows) Python3でのUnicodeEncodeErrorの原因と回避方法
https://qiita.com/butada/items/33db39ced989c2ebf644

コメント