问题描述
我经常使用以下命令快速启动 Web 服务器以提供当前文件夹中的 HTML 内容(用于本地测试):
I often use the following to quickly fire up a web server to serve HTML content from the current folder (for local testing):
python -m SimpleHTTPServer 8000
是否有一种相当简单的方法可以做到这一点,但让服务器使用 UTF-8 编码而不是系统默认编码来提供文件?
Is there a reasonably simple way I can do this, but have the server serve the files with a UTF-8 encoding rather than the system default?
推荐答案
遇到同样的问题,以下代码对我有用.
Had the same problem, the following code worked for me.
要使用 UTF-8 编码启动 SimpleHTTPServer,只需在终端中复制/粘贴以下内容(对于 Python 2).
To start a SimpleHTTPServer with UTF-8 encoding, simply copy/paste the following in terminal (for Python 2).
python -c "import SimpleHTTPServer; m = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map; m[''] = 'text/plain'; m.update(dict([(k, v + ';charset=UTF-8') for k, v in m.items()])); SimpleHTTPServer.test();"
事先确保您的 HTML 文件中有正确的字符集.
Ensure that you have the correct charset in your HTML files beforehand.
编辑:Python 3 更新:
EDIT: Update for Python 3:
python3 -c "from http.server import test, SimpleHTTPRequestHandler as RH; RH.extensions_map={k:v+';charset=UTF-8' for k,v in RH.extensions_map.items()}; test(RH)"
test
函数还接受诸如 port
和 bind
之类的参数,以便可以指定要侦听的地址和端口.
The test
function also accepts arguments like port
and bind
so that it's possible to specify the address and the port to listen on.
这篇关于如何使用 Python SimpleHTTPServer 以 UTF-8 编码提供文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!