Python의 특성 파일 (Java 특성과 유사)
다음과 같은 형식 ( .properties 또는 .ini )이 제공됩니다.
propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN
를 들어 자바 이 속성 클래스는 그 위의 형식과 구문 분석 / 상호 작용에 제공 기능.
파이썬 의 표준 라이브러리 (2.x)에 비슷한 것이 있습니까?
그렇지 않은 경우 다른 대안이 있습니까?
.ini 파일의 경우 .ini 파일 과 호환되는 형식을 제공하는 ConfigParser 모듈이 있습니다.
어쨌든 완전한 .properties 파일을 구문 분석하는 데 사용할 수있는 것은 없습니다.이를 수행해야 할 때 단순히 jython을 사용합니다 (스크립팅에 대해 이야기하고 있습니다).
이 작업을 수행 할 수 있었지만 아무도이 작업 ConfigParser
을 수행하는 방법에 대한 예를 보여주지 않았으므로 속성 파일의 간단한 파이썬 리더와 속성 파일의 예가 있습니다. 확장명은 여전히 .properties
이지만 .ini 파일에서 볼 수있는 것과 비슷한 섹션 헤더를 추가해야했습니다. 약간의 끔찍한 일이지만 작동합니다.
파이썬 파일 : 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을 참조하십시오.
자바 속성 파일은 종종 유효한 파이썬 코드입니다. myconfig.properties 파일의 이름을 myconfig.py로 바꿀 수 있습니다. 그런 다음 파일을 다음과 같이 가져 오십시오.
import myconfig
속성에 직접 액세스
print myconfig.propertyName1
나는 이것이 매우 오래된 질문이라는 것을 알고 있지만 지금 당장 필요하며 대부분의 사용 사례 (모두는 아님)를 다루는 순수 파이썬 솔루션 인 자체 솔루션을 구현하기로 결정했습니다.
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
다음 형식으로 파일을 구문 분석하기 위해 ':'로 변경할 수 있습니다 .
key : value
코드는 다음과 같이 올바르게 줄을 구문 분석합니다.
url = "http://my-host.com"
name = Paul = Pablo
# This comment line will be ignored
당신은 다음과 같이 받아 들일 것입니다 :
{"url": "http://my-host.com", "name": "Paul = Pablo" }
파일 형식의 옵션이 있다면 언급 한대로 .ini 및 Python의 ConfigParser를 사용하는 것이 좋습니다. Java .properties 파일과의 호환성이 필요한 경우 jprops 라는 라이브러리를 작성했습니다 . 우리는 pyjavaproperties를 사용하고 있었지만 다양한 제한이 발생하면 내 구현을 끝내게되었습니다. 유니 코드 지원 및 이스케이프 시퀀스 지원 향상을 포함하여 .properties 형식을 완벽하게 지원합니다. pyjavaproperties는 디스크의 실제 파일에서만 작동하는 반면 Jprops는 파일과 유사한 객체를 구문 분석 할 수 있습니다.
이것은 정확히 속성은 아니지만 Python에는 구성 파일을 구문 분석하기위한 멋진 라이브러리 가 있습니다. 이 레시피 : java.util.Properties의 파이썬 대체 도 참조하십시오 .
여러 줄 속성이없고 매우 간단한 요구 사항이 있으면 몇 줄의 코드로 해결할 수 있습니다.
파일 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}
내 프로젝트에 대한 링크는 https://sourceforge.net/projects/pyproperties/ 입니다. Python 3.x 용 * .properties 파일 작업을위한 메소드가있는 라이브러리입니다.
그러나 java.util.Properties를 기반으로하지 않습니다.
이것은 java.util.Propeties의 일대일 대체품입니다.
문서에서 :
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.
이것은 내 프로젝트에서하는 일입니다. 프로젝트에 사용 된 모든 공통 변수 / 속성을 포함하는 properties.py라는 다른 .py 파일을 만들고 파일 에서이 변수를 참조해야합니다.
from properties import *(or anything you need)
dev 위치를 자주 변경하고 일부 공통 변수는 로컬 환경과 관련이있을 때 svn의 평화를 유지하기 위해이 방법을 사용했습니다. 나에게 잘 작동하지만 공식 개발 환경 등에이 방법이 제안 될지는 확실하지 않습니다.
Java의 Properties 클래스와 거의 비슷한 파이썬 모듈을 만들었습니다 (실제로 $ {variable-reference}를 사용하여 이미 정의 된 속성을 참조 할 수 있도록하는 Spring의 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')
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.properties
파일 레이아웃 :
[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의 값을 얻으려면 : 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'섹션의 키입니다.)
import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)
test.json의 내용 : { "host": "127.0.0.1", "user": "jms"}
아래 2 줄의 코드는 Python List Comprehension을 사용하여 'java 스타일'속성 파일을로드하는 방법을 보여줍니다.
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/
파이썬 모듈에서 사전을 만들고 모든 것을 저장하고 액세스하십시오 (예 :
dict = {
'portalPath' : 'www.xyx.com',
'elementID': 'submit'}
이제 액세스하려면 다음을 수행하면됩니다.
submitButton = driver.find_element_by_id(dict['elementID'])
다음과 같이 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
이것은 파일을 구문 분석하고 주석과 키가 아닌 값 줄을 건너 뛰는 환경 변수로 설정하여 hg를 지정하는 스위치를 추가 한 것입니다.
- -h 또는 --help 인쇄 사용법 요약
- -c 주석을 식별하는 char을 지정하십시오.
- -s prop 파일에서 키와 값을 구분하는 구분자
파싱해야 할 속성 파일을 지정하십시오. 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 has released the Typesafe Config library, which parses properties files and also some JSON-based extensions. Lightbend's library is only for the JVM, but it seems to be widely adopted and there are now ports in many languages, including Python: https://github.com/chimpler/pyhocon
You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.
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
this works for me.
from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']
i have used this, this library is very useful
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'
I followed configparser approach and it worked quite well for me. Created one PropertyReader file and used config parser there to ready property to corresponding to each section.
**Used Python 2.7
Content of PropertyReader.py file:
#!/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
Content of read schema file:
from PropertyReader import *
class ReadSchema:
print PropertyReader().readProperty('source1_section','source_name1')
print PropertyReader().readProperty('source2_section','sn2_sc1_tb')
Content of .properties file:
[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
참고URL : https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
'programing tip' 카테고리의 다른 글
비표준 포트로 원격 저장소 사용 (0) | 2020.07.12 |
---|---|
LINQ를 사용하여 컬렉션을 n 개의 부분으로 나누시겠습니까? (0) | 2020.07.12 |
값이 null 인 맵 항목을 무시하는 Gson (0) | 2020.07.12 |
고스트 이미지의 드래그를 방지하는 CSS / JS? (0) | 2020.07.12 |
최적의 코드 너비에 대한 연구? (0) | 2020.07.12 |