programing

ConfigParser에서 대소 문자를 유지 하시겠습니까?

nasanasas 2020. 10. 19. 08:08
반응형

ConfigParser에서 대소 문자를 유지 하시겠습니까?


Python의 ConfigParser 모듈을 사용하여 설정을 저장 하려고했습니다 . 내 앱의 경우 섹션에서 각 이름의 대소 문자를 유지하는 것이 중요합니다. 문서에서는 str ()을 ConfigParser.optionxform ()에 전달 하면이를 수행 할 수 있다고 언급 하지만 저에게는 작동하지 않습니다. 이름은 모두 소문자입니다. 내가 뭔가를 놓치고 있습니까?

<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz

내가 얻는 것의 파이썬 의사 코드 :

import ConfigParser,os

def get_config():
   config = ConfigParser.ConfigParser()
   config.optionxform(str())
    try:
        config.read(os.path.expanduser('~/.myrc'))
        return config
    except Exception, e:
        log.error(e)

c = get_config()  
print c.options('rules')
[('monkey', 'foo'), ('ferret', 'baz')]

설명서가 혼란 스럽습니다. 이것이 의미하는 바는 다음과 같습니다.

import ConfigParser, os
def get_config():
    config = ConfigParser.ConfigParser()
    config.optionxform=str
    try:
        config.read(os.path.expanduser('~/.myrc'))
        return config
    except Exception, e:
        log.error(e)

c = get_config()  
print c.options('rules')

즉, optionxform을 호출하는 대신 재정의합니다. 재정의는 하위 클래스 또는 인스턴스에서 수행 할 수 있습니다. 재정의 할 때 함수를 호출 한 결과가 아닌 함수로 설정합니다.

이제 이것을 버그로 보고 했으며 이후 수정되었습니다.


나를 위해 객체를 만든 직후 optionxform을 설정했습니다.

config = ConfigParser.RawConfigParser()
config.optionxform = str 

코드에 추가 :

config.optionxform = lambda option: option  # preserve case for letters

이 질문에 대한 답을 알고 있지만 일부 사람들은이 솔루션이 유용하다고 생각할 수 있습니다. 기존 ConfigParser 클래스를 쉽게 대체 할 수있는 클래스입니다.

@OozeMeister의 제안을 통합하도록 편집 :

class CaseConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

사용법은 일반 ConfigParser와 동일합니다.

parser = CaseConfigParser()
parser.read(something)

이것은 당신이 새로운을 만들 때마다 optionxform을 설정할 필요가 없도록하기 위해서 ConfigParser입니다. 이것은 일종의 지루한 일입니다.


경고:

ConfigParser에서 기본값을 사용하는 경우, 즉 :

config = ConfigParser.SafeConfigParser({'FOO_BAZ': 'bar'})

그런 다음 다음을 사용하여 구문 분석기의 대소 문자를 구분하도록 시도하십시오.

config.optionxform = str

구성 파일의 모든 옵션은 대소 문자를 유지하지만 FOO_BAZ소문자로 변환됩니다.

기본값도 대소 문자를 유지하려면 @icedtrees 대답과 같은 하위 클래스를 사용하십시오.

class CaseConfigParser(ConfigParser.SafeConfigParser):
    def optionxform(self, optionstr):
        return optionstr

config = CaseConfigParser({'FOO_BAZ': 'bar'})

이제 FOO_BAZ케이스를 유지하고 InterpolationMissingOptionError 가 발생하지 않습니다 .

참고URL : https://stackoverflow.com/questions/1611799/preserve-case-in-configparser

반응형