【问题标题】:can't print special chars in Python (encoding, special characters, lighttpd)无法在 Python 中打印特殊字符(编码、特殊字符、lighttpd)
【发布时间】:2013-10-21 19:52:00
【问题描述】:

我在打印特殊字符时遇到问题。 如果我想打印一个包含特殊字符的简单字符串并在浏览器中打开 python 文件,则该字符串不会显示。 我试着把

#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-

在所有可能的组合中都位于顶部 - 不起作用。 我尝试了使用标准输出和使用 .encode('utf8') 对我的字符串进行编码等解决方案。 最后一个解决方案对我有帮助,但是我的字符串随后以字节字符串形式呈现,我需要移交 JSON,所以我不想打印带有特殊字符的空白 JSON 字符串。 是否有可能是 lighttpd 存在问题,不允许我以 UTF-8 打印?我必须先更改 lighttpd.conf 吗?

Atm 我的配置文件如下所示:

server.modules = (
        "mod_access",
        "mod_alias",
        "mod_compress",
        "mod_redirect",
#       "mod_rewrite",
)

server.document-root        = "/var/www"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"

index-file.names            = ( "index.php", "index.html",
                                "index.htm", "default.htm",
                               " index.lighttpd.html" )

url.access-deny             = ( "~", ".inc" )

static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" , ".py")

## Use ipv6 if available
#include_shell "/usr/share/lighttpd/use-ipv6.pl"

dir-listing.encoding        = "utf-8"
server.dir-listing          = "enable"

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "text/plain; charset=utf-8", "text/html; charset=utf-8", "text/css; charset=utf-8", "text/xml; charset=utf-8", "text/javascript; charset=utf-8", "text/x-js", "application/x$
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

【问题讨论】:

  • 只是为了确定:当你说“在我的浏览器中打开 python 文件”时,你的意思是 1)查看 python 文件的源代码还是 2)查看执行的 python 脚本的输出作为 CGI ?如果 2):您尝试过在源代码中使用文字,但是对于用户提交的字符串(例如,带有 POST 的简单表单)会发生什么?我们可以看到您脚本的原始输出(HTTP 标头等)吗?
  • 2) 输出在一个文件中打开(它不是直接在浏览器中执行的,我不太明白)。如果我使用特殊字符,文件中的输出完全为空,例如print("ätzend")

标签: python encoding lighttpd


【解决方案1】:

您使用魔术注释声明的编码被Python用来解释您的字符串文字。但你只是完成了一半。 您的文件必须实际编码为 utf-8 才能正常工作。

使用好的文本编辑器(例如 Notepad++),您可以控制文件在磁盘上的实际编码方式。

请注意,尽管您检查是否使用了正确的编码是一个雷区:您的字符串可能会经过文件存储,然后在发送到浏览器之前会经过各种表示形式(例如变量、数据库等)(其中涉及 Content-Type 声明和潜在的自动检测)。我强烈建议您分别检查所有这些步骤。

【讨论】:

  • 我正在使用 Linux Ubuntu 开发 Eclipse Kepler。我使用 Python 3.3.2 和 Lighttpd。如果我打印出像“ärgerlich”这样的简单字符串,它不会在我的 Firefox 浏览器中显示任何内容。
【解决方案2】:

终于找到了解决办法:

output = message
json.dumps(output)
return output

无法工作:-)

output = message
return json.dumps(output)

是返回json的正确方式。

【讨论】:

    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 2016-10-19
    • 2013-06-07
    • 1970-01-01
    • 2013-08-12
    • 2012-12-09
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多