Python3中遇到UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in ordinal not in range(128) Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)

Original link: https://blog.csdn.net/th_num/article/details/80685389

Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)

But running code on windows is normal.
The reason is because of the linux system language.
Checked the system environment code
>>> import sys
>>> sys.stdout.encoding
'US-ASCII'
     
      
      
  • 1
  • 2
  • 3

And another machine that can print normally is en_US.UTF-8

Solution

(1) Set the environment variable LANG

The way to set environment variables on Linux or Mac is the same. Edit the ~/.bash_profile file ('~' refers to the default directory after the user logs in) and add a line:

export LANG="en_US.UTF-8"
     
      
      
  • 1

Reopen the command line console after saving and exiting

(2) Use PYTHONIOENCODING

Add the parameter PYTHONIOENCODING=utf-8 python test.py before running the python command

The explanation of this parameter can be found in the official document:
https://docs.python.org/3.6/using/cmdline.html#envvar-PYTHONIOENCODING

(3) Redefine standard output

Add sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) to the code, so that the code becomes:

import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
print('中文')
     
      
      
  • 1
  • 2
  • 3
  • 4

Guess you like

Origin blog.csdn.net/stay_foolish12/article/details/111929795