Python 3 不读取新服务器上的 unicode 文件 [英] Python 3 doesn't read unicode file on a new server

查看:34
本文介绍了Python 3 不读取新服务器上的 unicode 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页由一个脚本提供,该脚本动态导入一堆文件

尝试:with open (filename, 'r') as f:exec(f.read())除了 IOError:通过

(实际上,你能提出一种更好的导入文件的方法吗?我确定有一个.)

有时文件有不同语言的字符串,比如

#language.ru 的内容title = "Название"

那些都保存为 UTF-8 文件.Python 在命令行中运行脚本或从我的 MacBook 提供页面没有问题:

<前>OK: [服务器命令行] python3.0 page.py/index.ru好的:http://whitebox.local/index.ru

但是当尝试从我们刚移动到的服务器提供页面时它会抛出错误:

<前>157 尝试:158 with open (filename, 'r') as f:第159话160 除了 IOError:通过161/usr/local/lib/python3.0/io.py in read(self=, n=-1)...UnicodeDecodeError:ascii"编解码器无法解码位置 627 中的字节 0xe1:序号不在范围内(128)

所有文件都是从我的笔记本电脑中复制的,Apache 为它们提供了完美的服务.是什么原因?

更新:我发现 open() 的默认编码是平台相关的,所以它在我的笔记本电脑和 上是 utf8>ascii 在服务器上.我想知道在 Python 3 中是否有每个程序的函数来设置它(sys.setdefaultencodingsite 模块中使用,然后从命名空间中删除).

解决方案

使用 open(filename, 'r', encoding='utf8').请参阅 Python 3 文档打开.

My webpages are served by a script that dynamically imports a bunch of files with

try:
    with open (filename, 'r') as f:
        exec(f.read())
except IOError: pass

(actually, can you suggest a better method of importing a file? I'm sure there is one.)

Sometimes the files have strings in different languages, like

# contents of language.ru
title = "Название"

Those were all saved as UTF-8 files. Python has no problem running the script in command line or serving a page from my MacBook:

    OK: [server command line] python3.0 page.py /index.ru
    OK: http://whitebox.local/index.ru

but it throws an error when trying to serve a page from a server we just moved to:

      157     try:
      158         with open (filename, 'r') as f:
      159             exec(f.read())
      160     except IOError: pass
      161 
      /usr/local/lib/python3.0/io.py in read(self=, n=-1)
      ...
      UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 627: ordinal not in range(128) 

All the files were copied from my laptop where they were perfectly served by Apache. What is the reason?

Update: I found out the default encoding for open() is platform-dependent so it was utf8 on my laptop and ascii on server. I wonder if there is a per-program function to set it in Python 3 (sys.setdefaultencoding is used in site module and then deleted from the namespace).

解决方案

Use open(filename, 'r', encoding='utf8'). See Python 3 docs for open.

这篇关于Python 3 不读取新服务器上的 unicode 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆