我有一個python程序運行得很好。它連接到幾個網站並輸出所需的信息。由於並非所有網站都使用utf-8進行編碼,因此我正在從頭文件請求字符集,並使用unicode(string, encoding)
方法進行解碼(我不確定是否採用適當的方式來完成此操作,但工作得很好)。當我運行python程序時,我收不到?標記和它工作正常。但是,當我運行使用PHP的system
功能的程序,我收到此錯誤:php系統,蟒蛇和utf-8
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0131' in position 41: ordinal not in range(128)
這是一個Python特定的錯誤,但什麼讓我困惑的是,我當我運行使用終端程序不會收到此錯誤。我只有在使用php的system
函數並從php調用程序時纔會收到此消息。這個問題背後的原因是什麼?
這裏是一個示例代碼:
PHP代碼調用Python程序:
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
這可能是一個環境變量。 –