programing

python의 속성 파일(Java Properties와 유사)

oldcodes 2023. 7. 18. 21:56
반응형

python의 속성 파일(Java Properties와 유사)

다음 형식(.properties 또는 .ini)을 지정합니다.

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN

Java의 경우 위 형식을 구문 분석/상호 작용하는 기능을 제공하는 Properties 클래스가 있습니다.

파이썬의 표준 라이브러리(2.x)에 비슷한 것이 있습니까?

그렇지 않다면 다른 대안은 무엇입니까?

저는 이것을 사용할 수 있었습니다.ConfigParser아무도 이것을 하는 방법에 대한 예를 보여주지 않았기 때문에, 여기 속성 파일의 간단한 파이썬 리더와 속성 파일의 예가 있습니다.확장이 여전히 유지됩니다..properties하지만 .ini 파일에서 보는 것과 유사한 섹션 헤더를 추가해야 했습니다.약간의 사생아화이지만, 효과가 있습니다.

python 일파:PythonPropertyReader.py

#!/usr/bin/python    
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')

print config.get('DatabaseSection', 'database.dbname');

파일: 속성파:ConfigFile.properties

[DatabaseSection]
database.dbname=unitTest
database.user=root
database.password=

자세한 기능은 https://docs.python.org/2/library/configparser.html 을 참조하십시오.

위해서.ini호환 가능한 형식을 제공하는 모듈이 있습니다..inifiles 파일

어쨌든 파싱 완료에 사용할 수 있는 항목이 없습니다..properties파일, 그렇게 해야 할 때는 단순히 jython을 사용합니다(스크립팅에 대해 말하는 것입니다).

이것이 매우 오래된 질문이라는 것을 알고 있지만, 지금 당장 필요합니다. 그리고 대부분의 사용 사례를 다루는 순수 파이썬 솔루션을 구현하기로 결정했습니다.

def load_properties(filepath, sep='=', comment_char='#'):
    """
    Read the file passed as parameter as a properties file.
    """
    props = {}
    with open(filepath, "rt") as f:
        for line in f:
            l = line.strip()
            if l and not l.startswith(comment_char):
                key_value = l.split(sep)
                key = key_value[0].strip()
                value = sep.join(key_value[1:]).strip().strip('"') 
                props[key] = value 
    return props

변경할 수 .sep합니다. to ':'는 파일 형식입니다.

key : value

코드는 다음과 같은 행을 올바르게 구문 분석합니다.

url = "http://my-host.com"
name = Paul = Pablo
# This comment line will be ignored

다음을 사용하여 받아쓰기를 수행할 수 있습니다.

{"url": "http://my-host.com", "name": "Paul = Pablo" }

Java 속성 파일은 종종 유효한 파이썬 코드이기도 합니다.myconfig.properties 파일의 이름을 myconfig.py 으로 변경할 수 있습니다.그럼 이렇게 파일을 가져오세요.

import myconfig

속성에 직접 액세스할 수 있습니다.

print myconfig.propertyName1

다중 줄 속성이 없고 매우 간단한 요구 사항이 있는 경우 몇 줄의 코드로 해결할 수 있습니다.

t.properties:

a=b
c=d
e=f

파이썬 코드:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}

만약 당신이 파일 형식의 옵션을 가지고 있다면 언급한 대로 .ini와 Python의 ConfigParser를 사용하는 것을 제안합니다.Java .properties 파일과의 호환성이 필요하다면 jprops라는 라이브러리를 작성했습니다.우리는 pyjava 속성을 사용하고 있었지만, 여러 가지 한계에 부딪힌 후에 나만의 속성을 구현하게 되었습니다.Unicode 지원 및 이스케이프 시퀀스 지원 향상을 포함하여 .properties 형식을 완전히 지원합니다.Jprops는 파일과 유사한 개체를 구문 분석할 수 있지만 pyjava 속성은 디스크의 실제 파일에서만 작동합니다.

이것은 정확히 속성은 아니지만 Python에는 구성 파일을 구문 분석할 수 있는 훌륭한 라이브러리가 있습니다.다음 레시피도 참조하십시오.java.util의 파이썬 대체 버전입니다.속성.

저는 이것을 사용했습니다, 이 도서관은 매우 유용합니다.

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'

제 프로젝트에 대한 링크는 https://sourceforge.net/projects/pyproperties/ 입니다: https://sourceforge.net/projects/pyproperties/ .이 라이브러리는 Python 3.x용 *.properties 파일로 작업하기 위한 메서드가 포함된 라이브러리입니다.

그러나 java.util을 기반으로 하지 않습니다.특성.

이것은 java.util을 일대일로 대체한 입니다.프러티

문서에서:

  def __parse(self, lines):
        """ Parse a list of lines and create
        an internal property dictionary """

        # Every line in the file must consist of either a comment
        # or a key-value pair. A key-value pair is a line consisting
        # of a key which is a combination of non-white space characters
        # The separator character between key-value pairs is a '=',
        # ':' or a whitespace character not including the newline.
        # If the '=' or ':' characters are found, in the line, even
        # keys containing whitespace chars are allowed.

        # A line with only a key according to the rules above is also
        # fine. In such case, the value is considered as the empty string.
        # In order to include characters '=' or ':' in a key or value,
        # they have to be properly escaped using the backslash character.

        # Some examples of valid key-value pairs:
        #
        # key     value
        # key=value
        # key:value
        # key     value1,value2,value3
        # key     value1,value2,value3 \
        #         value4, value5
        # key
        # This key= this value
        # key = value1 value2 value3

        # Any line that starts with a '#' is considerered a comment
        # and skipped. Also any trailing or preceding whitespaces
        # are removed from the key/value.

        # This is a line parser. It parses the
        # contents like by line.

에서 파일과 같은 개체를 사용할 수 있습니다.ConfigParser.RawConfigParser.readfp여기에 정의됨 -> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp

재하는클정정을 재정의하는 합니다.readline속성 파일의 실제 내용 앞에 섹션 이름을 추가합니다.

저는 그것을 반으로 포장했습니다.dict정의된 모든 속성 중에서.

import ConfigParser

class PropertiesReader(object):

    def __init__(self, properties_file_name):
        self.name = properties_file_name
        self.main_section = 'main'

        # Add dummy section on top
        self.lines = [ '[%s]\n' % self.main_section ]

        with open(properties_file_name) as f:
            self.lines.extend(f.readlines())

        # This makes sure that iterator in readfp stops
        self.lines.append('')

    def readline(self):
        return self.lines.pop(0)

    def read_properties(self):
        config = ConfigParser.RawConfigParser()

        # Without next line the property names will be lowercased
        config.optionxform = str

        config.readfp(self)
        return dict(config.items(self.main_section))

if __name__ == '__main__':
    print PropertiesReader('/path/to/file.properties').read_properties()

속성 파일의 섹션에서 모든 값을 간단한 방법으로 읽어야 하는 경우:

당신의.config.propertieslayout : 파일:

[SECTION_NAME]  
key1 = value1  
key2 = value2  

코드:

   import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.properties file')

   details_dict = dict(config.items('SECTION_NAME'))

그러면 키가 구성 파일과 동일한 사전과 해당 값이 제공됩니다.

details_dict다음과 같습니다.

{'key1':'value1', 'key2':'value2'}

: key1은 key1입니다.details_dict['key1']

이 모든 것을 구성 파일에서 해당 섹션을 한 번만 읽는 메소드에 넣습니다(프로그램 실행 중에 메소드가 처음 호출될 때).

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict

이제 위의 함수를 호출하여 필요한 키 값을 얻습니다.

config_details = get_config_dict()
key_1_value = config_details['key1'] 

-------------------------------------------------------------

위에서 언급한 접근 방식을 확장하고 섹션별로 자동으로 읽은 다음 섹션 이름과 키 이름으로 액세스합니다.

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = dict()

        for section in config.sections():
            get_config_section.section_dict[section] = 
                             dict(config.items(section))

    return get_config_section.section_dict

액세스하기:

config_dict = get_config_section()

port = config_dict['DB']['port'] 

(여기서 'DB'는 구성 파일의 섹션 이름이고 'port'는 섹션 'DB' 아래의 키입니다.)

python 모듈에서 사전을 만들고 모든 것을 저장한 다음 액세스합니다. 예:

dict = {
       'portalPath' : 'www.xyx.com',
       'elementID': 'submit'}

이제 액세스하려면 다음 작업을 간단히 수행할 수 있습니다.

submitButton = driver.find_element_by_id(dict['elementID'])

내 Javaini 파일에 섹션 헤더가 없어서 결과적으로 받아쓰기를 원했습니다.그래서 저는 "[ini]" 섹션을 삽입하고 기본 구성 라이브러리가 제 역할을 하도록 했습니다.

eclipse IDE.metadata 디렉토리의 version.ini를 예로 들어 보겠습니다.

#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800
# 'injected' ini section
[ini]
#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800

결과가 딕트로 변환됩니다.

from configparser import ConfigParser

@staticmethod
    def readPropertyFile(path):
        # https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
        config = ConfigParser()
        s_config= open(path, 'r').read()
        s_config="[ini]\n%s" % s_config
        # https://stackoverflow.com/a/36841741/1497139
        config.read_string(s_config)
        items=config.items('ini')
        itemDict={}
        for key,value in items:
            itemDict[key]=value
        return itemDict

이것이 제 프로젝트에서 제가 하고 있는 일입니다.저는 속성이라는 다른 .py 파일을 만듭니다.프로젝트에서 사용한 모든 공통 변수/속성을 포함하는 py, 그리고 어떤 파일에서든 이 변수들을 참조해야 합니다.

from properties import *(or anything you need)

개발 위치를 자주 변경할 때 이 방법을 사용하여 svn 평화를 유지했으며 일부 일반적인 변수는 로컬 환경과 상당히 관련되어 있었습니다.저는 잘 작동하지만 이 방법이 정식 개발 환경 등에 제안될지는 잘 모르겠습니다.

import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)

test.json의 내용: {"host": "127.0.0.1", "user": "jms"}

Java의 Properties 클래스와 거의 유사한 파이썬 모듈을 만들었습니다(실제로 ${variable-reference}를 사용하여 이미 정의된 속성을 참조할 수 있는 봄의 PropertyPlaceholderConfigurer와 같습니다).

편집 : 명령을 실행하여 이 패키지를 설치할 수 있습니다(현재 python 3용으로 테스트됨).
pip install property

프로젝트는 GitHub에서 호스팅됩니다.

예: (자세한 설명서는 여기에서 확인할 수 있습니다)

my_file.properties 파일에 다음 속성이 정의되어 있다고 가정합니다.

foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge

위의 속성을 로드하는 코드

from properties.p import Property

prop = Property()
# Simply load it into a dictionary
dic_prop = prop.load_property_files('my_file.properties')

아래 두 줄의 코드는 Python List Comprehension을 사용하여 'java style' 속성 파일을 로드하는 방법을 보여줍니다.

split_properties=[line.split("=") for line in open('/<path_to_property_file>)]
properties={key: value for key,value in split_properties }

자세한 내용은 아래 게시물을 참조하십시오. https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/

아래와 같이 구성 파일에서 읽기 위해 argparse와 함께 "fromfile_messages_chars" 매개 변수를 사용할 수 있습니다.

temp.py

parser = argparse.ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument('--a')
parser.add_argument('--b')
args = parser.parse_args()
print(args.a)
print(args.b)

구성 파일

--a
hello
--b
hello dear

실행 명령

python temp.py "#config"

- https://pypi.org/project/property/ 을 사용할 수 있습니다.

- 예 -my_file.properties

foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge
long = a very long property that is described in the property file which takes up \
multiple lines can be defined by the escape character as it is done here
url=example.com/api?auth_token=xyz
user_dir=${HOME}/test
unresolved = ${HOME}/files/${id}/${bar}/
fname_template = /opt/myapp/{arch}/ext/{objid}.dat

코드

from properties.p import Property


## set use_env to evaluate properties from shell / os environment
prop = Property(use_env = True)
dic_prop = prop.load_property_files('my_file.properties')

## Read multiple files
## dic_prop = prop.load_property_files('file1', 'file2')


print(dic_prop)

# Output

# {'foo': 'I am awesome', 'bar': 'fudge-bar', 'chocolate': 'fudge',
#  'long': 'a very long property that is described in the property file which takes up multiple lines
#  can be defined by the escape character as it is done here', 'url': 'example.com/api?auth_token=xyz',
#  'user_dir': '/home/user/test',
#  'unresolved': '/home/user/files/${id}/fudge-bar/',
#  'fname_template': '/opt/myapp/{arch}/ext/{objid}.dat'}

저는 다음과 같이 ConfigParser를 사용하여 이 작업을 수행했습니다.코드는 BaseTest가 배치된 동일한 디렉토리에 config.prop라는 파일이 있다고 가정합니다.

config.prop

[CredentialSection]
app.name=MyAppName

BaseTest.py :

import unittest
import ConfigParser

class BaseTest(unittest.TestCase):
    def setUp(self):
        __SECTION = 'CredentialSection'
        config = ConfigParser.ConfigParser()
        config.readfp(open('config.prop'))
        self.__app_name = config.get(__SECTION, 'app.name')

    def test1(self):
        print self.__app_name % This should print: MyAppName

이것은 내가 파일을 구문 분석하고 그것을 env 변수로 설정하기 위해 작성한 것이고 코멘트를 건너뛰고 nonkey value lines 스위치를 추가하여 hg:d를 지정합니다.

  • -hor --help 인쇄 사용 요약
  • -c 주석을 식별하는 문자 지정
  • -s 프로필에서 키와 값 사이의 구분 기호
  • 구문 분석해야 하는 속성 파일을 지정합니다(예: python EnvParamSet.py -c # -s = env.properties).

    import pipes
    import sys , getopt
    import os.path
    
    class Parsing :
    
            def __init__(self , seprator , commentChar , propFile):
            self.seprator = seprator
            self.commentChar = commentChar
            self.propFile  = propFile
    
        def  parseProp(self):
            prop = open(self.propFile,'rU')
            for line in prop :
                if line.startswith(self.commentChar)==False and  line.find(self.seprator) != -1  :
                    keyValue = line.split(self.seprator)
                    key =  keyValue[0].strip() 
                    value = keyValue[1].strip() 
                            print("export  %s=%s" % (str (key),pipes.quote(str(value))))
    
    
    
    
    class EnvParamSet:
    
        def main (argv):
    
            seprator = '='
            comment =  '#'
    
            if len(argv)  is 0:
                print "Please Specify properties file to be parsed "
                sys.exit()
            propFile=argv[-1] 
    
    
            try :
                opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
            except getopt.GetoptError,e:
                print str(e)
                print " possible  arguments  -s <key value sperator > -c < comment char >    <file> \n  Try -h or --help "
                sys.exit(2)
    
    
            if os.path.isfile(args[0])==False:
                print "File doesnt exist "
                sys.exit()
    
    
            for opt , arg  in opts :
                if opt in ("-h" , "--help"):
                    print " hg:d  \n -h or --help print usage summary \n -c Specify char that idetifes comment  \n -s Sperator between key and value in prop file \n  specify file  "
                    sys.exit()
                elif opt in ("-s" , "--seprator"):
                    seprator = arg 
                elif opt in ("-c"  , "--comment"):
                    comment  = arg
    
            p = Parsing( seprator, comment , propFile)
            p.parseProp()
    
        if __name__ == "__main__":
                main(sys.argv[1:])
    

Lightbend는 속성 파일과 일부 JSON 기반 확장자를 구문 분석하는 Typesafe Config 라이브러리를 릴리스했습니다.Lightbend의 라이브러리는 JVM 전용이지만 널리 채택된 것으로 보이며 현재 Python: https://github.com/chimpler/pyhocon 을 포함한 여러 언어로 된 포트가 있습니다.

@mvallebr의 수정된 코드인 다음 함수를 사용할 수 있습니다.속성 파일 주석을 준수하고 빈 새 줄을 무시하며 단일 키 값을 검색할 수 있습니다.

def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
    """
    Reads a .properties file and returns the key value pairs as dictionary.
    if key value is specified, then it will return its value alone.
    """
    with open(propertiesFile) as f:
        l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
        d = {key.strip(): value.strip() for key, value in l}

        if key:
            return d[key]
        else:
            return d

이것은 나에게 효과가 있습니다.

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']

저는 config parser 접근 방식을 따랐고 저에게는 꽤 잘 작동했습니다.하나의 PropertyReader 파일을 만들고 거기서 구성 파서를 사용하여 각 섹션에 해당하는 속성을 준비했습니다.

**Python 2.7 사용

PropertyReader.py 파일의 내용:

#!/usr/bin/python
import ConfigParser

class PropertyReader:

def readProperty(self, strSection, strKey):
    config = ConfigParser.RawConfigParser()
    config.read('ConfigFile.properties')
    strValue = config.get(strSection,strKey);
    print "Value captured for "+strKey+" :"+strValue
    return strValue

읽기 스키마 파일의 내용:

from PropertyReader import *

class ReadSchema:

print PropertyReader().readProperty('source1_section','source_name1')
print PropertyReader().readProperty('source2_section','sn2_sc1_tb')

.properties 파일의 내용:

[source1_section]
source_name1:module1
sn1_schema:schema1,schema2,schema3
sn1_sc1_tb:employee,department,location
sn1_sc2_tb:student,college,country

[source2_section]
source_name1:module2
sn2_schema:schema4,schema5,schema6
sn2_sc1_tb:employee,department,location
sn2_sc2_tb:student,college,country

사용할 수 있습니다.python-dotenv도서관.이 라이브러리는 에서 키-값 쌍을 읽습니다..env(따라서 정확히 a는 아닙니다..propertiesfile though) 파일이며 환경 변수로 설정할 수 있습니다.

다음은 공식 문서의 사용 예입니다.

from dotenv import load_dotenv

load_dotenv()  # take environment variables from .env.

# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.

언급URL : https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties

반응형