2011-09-09 3 views
3

저는 파이썬 프로그램이 잘 돌아가고 있습니다. 여러 웹 사이트에 연결하여 원하는 정보를 출력합니다. 모든 웹 사이트가 utf-8로 인코딩 된 것은 아니므로 헤더에서 charset을 요청하고 디코드하기 위해 unicode(string, encoding) 메서드를 사용하고 있습니다. (이 방법은 적절한 방법인지 잘 모르지만 잘 작동합니다). 내가 python 프로그램을 실행할 때 나는 no ??? 자국 및 ​​잘 작동합니다. 나는 PHP의 system 기능을 사용하여 프로그램을 실행할 때,이 오류가 나타납니다php system, python, utf-8

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

이것은 파이썬 특정 오류입니다하지만 나를 혼란은 내가 터미널을 사용하여 프로그램을 실행할 때이 오류가 없다는 것입니다 . 나는 PHP의 system 함수를 사용하고 php에서 프로그램을 호출 할 때만 이것을 받는다. 이 문제의 원인은 무엇일까요?

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

파이썬 코드 :

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 
+0

아마도 환경 변수 일 겁니다. –

답변

2

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.

이 왜 당신의 프로그램은 터미널에서 호출 할 때 작동합니다. 프로그램은 PHP에서 호출 할 때 실패하는 이유

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에서 호출 할 때 작동하게하려면 print에서 사용해야하는 인코딩을 명시해야합니다.

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을 설정할 수 있습니다 : 예를 들어, (터미널에 연결되지 않은 경우) utf-8으로 인코딩 된 출력을 원하는 명시 적으로 확인합니다. 그런 다음 코드는 변경하지 않고 (터미널과 PHP에서 호출 할 때 모두) 작동해야합니다.

+0

당신의 대답이 내 문제를 해결했습니다. 감사 – Shaokan

2

당신이 당신의 터미널에서 파이썬 스크립트를 실행, 터미널 파이썬 프로그램을 호출

PHP 코드 : 여기

은 샘플 코드 UTF8로 인코딩 될 가능성이 있습니다 (특히 Linux 또는 Mac을 사용하는 경우).

변수를 "some string with latin characters"으로 설정하면 해당 문자열이 기본 인코딩으로 인코딩됩니다. l은 UTF8이고 스크립트는 작동하지 않습니다.

약간의 팁 : 라틴 인코딩 된 문자열이 있고 유니 코드에 원하는 경우에 당신은 할 수 있습니다 :

variable.decode('latin1')

관련 문제