首页 > 解决方案 > 我的 python 代码中 Cp1252 编码的问题

问题描述

简介:我喜欢vim文本编辑器,python也是,所以我用vim编写脚本并通过git-bash终端运行它们,但是前两天我遇到了一个问题。当我通过 git-bash 终端运行脚本时,出现错误。但是,如果我通过 VSCode 中的集成终端运行脚本,它就可以工作。

首先,我认为我使用了错误的终端编码,然后我在终端中输入了语言环境,并得到以下输出(见附件A)。当我在 VSCode 终端中键入命令时,得到的输出完全相同,因此问题不在其中。

“嗯,它变得有趣了”,我想,并检查了我的 vimrc 配置文件,但它很好(见附件B)。我需要承认,我之前的编码没有问题,所以我想,问题出在 API 响应中使用的语言上,因为 cp1252 只能表示拉丁字符,但不能表示俄语!那么,有没有人有任何建议我该如何解决它?

代码:

import requests
import os


api_key = os.getenv('yandex_praktikum_api_key')


HEADERS = {
    'Authorization': f'OAuth {api_key}'
}


response = requests.get(
    'https://praktikum.yandex.ru/api/user_api/homework_statuses/',
    params={'from_date': 0},
    headers=HEADERS
)


print(response.text) # The issue happens here.

使用终端时出现错误:

User@DESKTOP-CVQ282P MINGW64 ~/Desktop
$ python backpool.py
Traceback (most recent call last):
  File "backpool.py", line 20, in <module>
    print(response.text)
  File "D:\Python3\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 63-69: character maps to <undefined>

正确的 API 响应,当我使用 VSCode 集成终端时:

User@DESKTOP-CVQ282P MINGW64 ~/Desktop
$ python backpool.py
{"source":"__response__","code":"not_authenticated","message":"Учетные данные не были предоставлены."}
# As you can see, there is the Russian language

A(语言环境命令):

User@DESKTOP-CVQ282P MINGW64 ~/Desktop
$ locale
LANG=ru_RU.UTF-8
LC_CTYPE="ru_RU.UTF-8"
LC_NUMERIC="ru_RU.UTF-8"
LC_TIME="ru_RU.UTF-8"
LC_COLLATE="ru_RU.UTF-8"
LC_MONETARY="ru_RU.UTF-8"
LC_MESSAGES="ru_RU.UTF-8"
LC_ALL=

B(完整的 vimrc):

set nocompatible
filetype off

" Configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" Delete all spaces at the end of all lines (PEP8 requirement)
autocmd BufWritePre *.py normal m`:%s/\s\+$//e ``

set backspace=indent,eol,start " always enable to use backspace

set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

set showtabline=2       " always show tabline (file names)
set nu                  " show line number to the left
set ruler               " show line and column number (at the bottom)
syntax on               " syntax highlighting
color delek             " set theme of syntax
set showcmd             " show (partial) command in status line

" Set path to file finding commands (find in current dir and subdirs)
:set path=.,,**

" Encoding and backup settings
set nobackup
set noswapfile
set encoding=utf-8
set termencoding=utf-8
set fileencodings=utf-8,cp1251

" turn relative line numbers on
:set relativenumber
:set rnu

" Cursor editing: set more solid cursor
let &t_SI.="\e[5 q" "SI = INSERT mode
let &t_SR.="\e[4 q" "SR = REPLACE mode
let &t_EI.="\e[1 q" "EI = NORMAL mode (ELSE)

PS目前我可以使用 VSCode 运行上面的代码,但不能使用终端。

标签: pythonencodingutf-8cp1252

解决方案


我终于解决了。在 python 和文本编辑器中都没有问题——它是在 Windows 10 编码中,所以我将它更改为 UTF-8。我认为,来自 Windows 的勇敢工程师绝对应该将所有国家的默认编码更改为 UTF ,包括俄罗斯。


推荐阅读