基本情况: Vultr $2.5/year, CentOS 7, 安装的是 Python3.6。
@app.route("/douban", methods=['GET'])
def doubanFM():
f = open('douban.txt', 'r')
txt = f.read()
lines = txt.split('# ')
lines = lines[:-1]
return random.choice(lines)
用 Python3.6 运行上面的代码,出现错误。其中,douban.txt 文件中大都为中文字符,.py 文件开头加了 #coding:utf-8。主要错误代码如下:
...
...
File "/usr/lib64/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib64/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/root/weather/app.py", line 32, in DoubanFM
txt = f.read()
File "/usr/lib64/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
后来没办法换用 CentOS 自带的 Python2 运行,没错误,能正常输出中文。但我很想知道为啥用 Python3.6 来运行就不行,求相应解决办法。