我在python 3中编码时遇到麻烦。当我在PC上测试时,我没有错误:
Python 3.7.3 (default, Jun 24 2019, 04:54:02)
[GCC 9.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> print(requests.get('https://www.kinopoisk.ru').text)
everything good.
但是,当我在VPS上运行此代码时,有以下错误:
Python 3.7.3 (default, Apr 3 2019, 19:16:38)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> print(requests.get('https://www.kinopoisk.ru').text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 393-401: ordinal not in range(256)
Python版本相同。我不知道发生了什么。
我该如何修复?
如果您的环境使用C OS posix语言环境,则python 3.7自动胁迫它向UTF-8 Aware Locale,根据PEP-538。
因此,您的PC似乎具有UTF-8
或C
语言环境集,而您的VPS使用latin-1
。
尝试在两台机器上的交互式Python会话中运行以下内容:
import sys
import locale
print(sys.getfilesystemencoding())
print(locale.getpreferredencoding())
它不想更改VPS上的语言环境,可以在其环境中设置PYTHONUTF8=1
,也可以使用Python使用-X utf-8
选项。