【问题标题】:php system, python and utf-8php系统、python和utf-8
【发布时间】:2011-11-13 19:45:45
【问题描述】:

我有一个运行良好的 python 程序。它连接到多个网站并输出所需的信息。由于并非所有网站都使用 utf-8 编码,因此我从标头请求字符集并使用unicode(string, encoding) 方法进行解码(我不确定它是否适合这样做,但效果很好)。当我运行 python 程序时,我没有收到 ???标记,它工作正常。但是当我使用 php 的 system 函数运行程序时,我收到了这个错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0131' in position 41: ordinal not in range(128)

这是一个特定于 python 的错误,但让我感到困惑的是,当我使用终端运行程序时,我没有收到此错误。只有当我使用 php 的 system 函数并从 php 调用程序时,我才会收到此消息。这个问题背后的原因可能是什么?

这是一个示例代码:

调用python程序的php代码:

system("python somefile.py $search") // where $search is the variable coming from an input

python 代码:

encoding = "iso-8859-9"
l = "some string here with latin characters"
print unicode("<div class='line'>%s</div>" % l, encoding)
# when I run this code from terminal it works perfect and I receive no ??? marks
# when I run this code from php, I receive the error above

【问题讨论】:

  • 可能是环境变量。

标签: php python encoding system decoding


【解决方案1】:

来自PrintFails wiki

当 Python 发现它的输出连接到终端时,它会设置 sys.stdout.encoding 终端编码的属性。印刷品 语句的处理程序将自动将 unicode 参数编码为 str 输出。

这就是为什么你的程序在从终端调用时可以工作的原因。

当 Python 没有检测到所需的字符集时 输出,它将 sys.stdout.encoding 设置为 None,并且 print 将调用 “ascii”编解码器。

这就是为什么你的程序在从 php.ini 调用时失败的原因。 要使其在从 php 调用时工作,您需要明确说明 print 应该使用什么编码。例如,要明确表示您希望以utf-8 编码的输出(当未连接到终端时):

ENCODING = sys.stdout.encoding if sys.stdout.encoding else 'utf-8'
print unicode("<div class='line'>%s</div>" % l, encoding).encode(ENCODING)

或者,您可以设置PYTHONIOENCODING environment variable。 然后你的代码应该可以在没有变化的情况下工作(无论是从终端还是从 php 调用时)。

【讨论】:

    【解决方案2】:

    当您在终端中运行 python 脚本时,您的终端很可能以 UTF8 编码(特别是如果您使用的是 linux 或 mac)。

    当您将l 变量设置为"some string with latin characters" 时,该字符串将被编码为默认编码,如果您使用的是终端,l 将是 UTF8,并且脚本不会崩溃。

    一个小提示:如果你有一个用 latin1 编码的字符串,并且你想用 unicode 编码,你可以这样做:

    variable.decode('latin1')

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 2015-05-28
      • 2012-07-26
      • 2012-06-01
      • 2017-05-07
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多