문제

configparser와의 문제는 계속됩니다. 유니 코드를 잘 지원하지 않는 것 같습니다. 구성 파일은 실제로 UTF-8으로 저장되지만 ConfigParser가 읽으면 다른 것으로 인코딩 된 것 같습니다. 나는 그것이 라틴어 -1이라고 생각했고 나는 우선했다 optionxform 도울 수 있습니다 :

-- configfile.cfg -- 
[rules]
Häjsan = 3
☃ = my snowman

-- myapp.py --
# -*- coding: utf-8 -*-  
import ConfigParser

def _optionxform(s):
    try:
        newstr = s.decode('latin-1')
        newstr = newstr.encode('utf-8')
        return newstr
    except Exception, e:
        print e

cfg = ConfigParser.ConfigParser()
cfg.optionxform = _optionxform    
cfg.read("myconfig") 

물론 구성을 읽으면 다음과 같습니다.

'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

나는 디코딩 'S'의 몇 가지 변형을 시도했지만 요점은 처음부터 유니 코드 객체이어야하기 때문에 요점이 멍청 해 보인다. 결국 구성 파일은 UTF-8입니까? Configparser 가이 DummyConfig 클래스로 스터브하여 파일을 읽는 방식에서 무언가가 잘못되었음을 확인했습니다. 내가 그것을 사용한다면, 모든 것이 좋은 유니 코드, 미세하고 댄디입니다.

-- config.py --
# -*- coding: utf-8 -*-                
apa = {'rules': [(u'Häjsan', 3), (u'☃', u'my snowman')]}

class DummyConfig(object):
    def sections(self):
        return apa.keys()
    def items(self, section):
       return apa[section]
    def add_section(self, apa):
        pass  
    def set(self, *args):
        pass  

이것을 일으킬 수있는 아이디어 또는 유니 코드를 더 잘 지원하는 다른 구성 모듈의 제안이 가장 환영합니다. 사용하고 싶지 않습니다 sys.setdefaultencoding()!

도움이 되었습니까?

해결책

그만큼 ConfigParser.readfp() 메소드는 파일 객체를 가져갈 수 있습니다. 코덱 모듈을 사용하여 올바른 인코딩으로 파일 객체를 열기 전에 아래와 같이 CONFIGPARSER로 전송하려고했습니다.

cfg.readfp(codecs.open("myconfig", "r", "utf8"))

파이썬 3.2 이상의 경우 readfp() 더 이상 사용되지 않습니다. 사용 read_file() 대신에.

다른 팁

덮어 쓰십시오 write 기능 RawConfigParser() 이와 같이:

class ConfigWithCoder(RawConfigParser):
def write(self, fp):
    """Write an .ini-format representation of the configuration state."""
    if self._defaults:
        fp.write("[%s]\n" % "DEFAULT")
        for (key, value) in self._defaults.items():
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
    for section in self._sections:
        fp.write("[%s]\n" % section)
        for (key, value) in self._sections[section].items():
            if key == "__name__":
                continue
            if (value is not None) or (self._optcre == self.OPTCRE):
                if type(value) == unicode:
                    value = ''.join(value).encode('utf-8')
                else:
                    value = str(value)
                value = value.replace('\n', '\n\t')
                key = " = ".join((key, value))
            fp.write("%s\n" % (key))
        fp.write("\n")

유니 코드 문자열을 값으로 읽고 쓸 때 구성 모듈이 끊어집니다. 나는 그것을 고치려고 노력했지만 파서가 작동하는 이상한 방식으로 잡혔다.

Python 2x의 Configparser 버전에 문제가있는 것 같습니다. 3x 버전에는이 문제가 없습니다. ~ 안에 Python Bug Tracker 의이 문제, 상태는 닫힙니다 + WontFix입니다.

configparser.py 파일 편집을 수정했습니다. 쓰기 메소드 (라인 412)에서 변경 :

key = " = ".join((key, str(value).replace('\n', '\n\t')))

~에 의해

key = " = ".join((key, str(value).decode('utf-8').replace('\n', '\n\t')))

그것이 실제 솔루션인지는 모르겠지만 Windows 7과 Ubuntu 15.04에서 테스트 한 것은 매력처럼 작동하며 두 시스템에서 동일한 .ini 파일과 공유하고 작업 할 수 있습니다.

파이썬에서 3.2 encoding 매개 변수가 소개되었습니다 read(), 이제 다음과 같이 사용할 수 있습니다.

cfg.read("myconfig", encoding='utf-8')

내가 한 일은 단지 :

file_name = file_name.decode("utf-8")
cfg.read(file_name)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top