编程语言
首页 > 编程语言> > php系统,python和utf-8

php系统,python和utf-8

作者:互联网

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

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

这是一个特定于python的错误,但令我困惑的是,当我使用终端运行程序时,我没有收到此错误.当我使用php的系统函数并从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

解决方法:

PrintFails wiki

When Python finds its output attached to a terminal, it sets the
sys.stdout.encoding attribute to the terminal’s encoding. The print
statement’s handler will automatically encode unicode arguments into
str output.

这就是您从终端调用程序时的工作原理.

When Python does not detect the desired character set of the
output, it sets sys.stdout.encoding to None, and print will invoke the
“ascii” codec.

这就是为什么你的程序从php调用失败的原因.
为了使它在从php调用时工作,你需要明确打印应该使用的编码.例如,要明确表示您希望以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调用时).

标签:decoding,python,php,encoding,system
来源: https://codeday.me/bug/20190903/1794674.html