Python 구성 파일 : 파일 형식 권장 사항이 있습니까? INI 형식이 여전히 적절합니까? 꽤 오래된 학교 같네요
Python 애플리케이션에 대한 구성 (키 / 값)을 저장해야하며 이러한 구성을 파일에 저장하는 가장 좋은 방법을 찾고 있습니다.
Python의 ConfigParser를 실행 하고 INI 파일 형식이 오늘날에도 여전히 적절한 지 궁금합니다! 최신 형식이 있습니까? 아니면 INI가 여전히 권장되는 방법입니까? (XML, JSON, ...)
여러분의 의견 / 추천을 공유 해주세요 ...
일반 Python 파일을 구성 파일로 사용하는 것이 좋습니다.
예 ( example.conf
) :
# use normal python comments
value1 = 32
value2 = u"A unicode value"
value3 = "A plain string value"
value4 = ["lists", "are", "handy"]
value5 = {"and": "so", "are": "dictionaries"}
프로그램에서 execfile
( 2.7 docs )를 사용하여 구성 파일을로드합니다 .
if __name__ == "__main__":
config = {}
execfile("example.conf", config)
# python 3: exec(open("example.conf").read(), config)
print config["value1"]
print config["value5"]
다음과 같은 이유로이 접근 방식을 좋아합니다.
- 간단한 경우 형식은 INI 스타일 구성 파일만큼 작성하기 쉽습니다. 또한 INI 파일과 중요한 특성을 공유합니다. 버전 제어에 매우 적합합니다 (XML 및 JSON에도 해당되지 않음).
- 실제 프로그래밍 언어로 구성 파일을 사용할 때 제공되는 유연성이 마음에 듭니다.
이 접근법은 널리 사용되며 몇 가지 예가 있습니다.
- 장고 사이트의 설정은 내부에 살고 settings.py . Django는를 사용하지 않고 AFAIK 를 읽고 실행
execfile
하는 데 사용 하지만 최종 결과는 동일합니다. 설정 파일 내의 코드가 실행됩니다.import
settings.py
- bash 쉘은
~/.bashrc
시작시 읽고 실행 합니다. - Python 인터프리터
site.py
는 시작시 가져 오기 (및 실행) 합니다.
INI는 완전히 정상이며 다른 사람들이 말했듯이 구성 파일의 형식은 실제로 사용 방법에 따라 다릅니다.
개인적으로 저는 YAML 의 팬입니다 : 간결하고 읽기 쉽고 유연합니다.
Google은 Google App Engine에서도 사용하기 때문에 내 열정을 공유하는 것 같습니다. 파이썬 파서가 여기 있습니다 .
사전 도 꽤 유명합니다. 기본적으로 해시 테이블입니다.
{"one": 1, "two": 2}
예입니다. 일종의 json처럼 보입니다.
그런 다음 mydict["one"]
1을 반환 하는 것과 같이 호출 할 수 있습니다 .
그런 다음 shelve 를 사용하여 사전을 파일에 저장할 수 있습니다 .
mydict = shelve.open(filename)
# then you can call it from there, like
mydict["one"]
따라서 ini 파일보다 다소 쉽습니다. 목록과 같은 항목을 추가하거나 옵션을 매우 쉽게 변경할 수 있으며 닫으면 다시 작성됩니다.
내가 의미하는 바에 대한 간단한 예는 다음과 같습니다.
import shelve
def main():
mydict = shelve.open("testfile")
mydict["newKey"] = value("some comment", 5)
print(mydict["newKey"].value)
print(mydict["newKey"].comment)
mydict.close()
class value():
def __init__(self, comment, value):
self.comment = comment
self.value = value
if __name__ == '__main__':
main()
This entirely depends on your requirements. If (as you say) all you need is key/value pairs, ini files (or other "plain" config files) will perfectly suit you. No, they are not outdated, as they are still in use.
XML/JSON is perfect if you have hierarchical structures and also want to use more sophisticated methods (e.g: XML file validation, namespaces, etc.).
Check out ConfigObj, its the slickest method I've found so far, and definitely more flexible than ConfigParser. Personally I'm not a fan of YAML based because its 'flexibility' makes it difficult to use with tools like Augeas.
It depends on how the config file will be used.
One of the advantages of INI files is that they are really easy to read and understand. It's much easier to make a mistake in JSON or XML file if you edit config by hand. PHP still uses INI files.
However, if you your config is not meant to be edited by hand, go with any format you like, because INI is not the easiest one to parse.
For completeness, you can also use a shell-style configuration format with the help of the "shlex" module. If you have a fixed set of configuration parameters then you can combine it with the "optparse" module.
from optparse import OptionParser
_o = OptionParser("%prog [options] configfiles...")
_o.add_option("--hostname", metavar="HOSTNAME", default="10.0.0.1")
_o.add_option("--username", metavar="USERNAME", default="admin")
_o.add_option("--password", metavar="PASSWORD", default="admin")
import shlex
def parse(filename, defaults):
opt, args = _o.parse_args(shlex.split(open(filename).read()), defaults)
return opt
if __name__ == "__main__":
import sys
values, args = _o.parse_args()
for arg in args:
values = parse(arg, values)
values, args = _o.parse_args(values = values)
for name in _o.defaults:
print name, "=", getattr(values, name)
The example shows how you can chain ini files for having a default set of values and user-defined redefinitions. So assume you have two files containing
file1.ini:
--hostname 10.2.3.4
--password admin-sc
file2.ini:
--username "foo bar"
--password "special key"
Then you can run ./configtest.py file1.ini file2.ini --password other
and the resulting values will have hostname as 10.2.3.4 and username as "foo bar" and password as "other". This variation for configuration settings comes in handy if you do already have an optparse-definition for your program parameters -> just reuse it and you can chain the values from the command line with the values from a config file and possibly some global config settings.
As an incentive, your configuration parameters are always documented and mistyped configuration parameters will come up early as an error, just as you can use the optparse-instance to precheck your default settings file (schema check). As a downside, there are no comments allowed in the ini and configuration elements are not easily substructured.Still your parser is essentially a one-liner.
I ran into same problem more than once. I love the idea of python file(s) as settings files, it's just simple, elegant and all fellow python devs like it. Same time not really convinced with execfile idea.
So I went ahead and created Converge.
It supports some advanced options but at it's heart it simple python module as settings file.
It's as simple as
- creating
default_settings.py
,prod_settings.py
pip install converge
import settings
'Nice programing' 카테고리의 다른 글
Rails 3에서 Rails 3.1로 업그레이드 (0) | 2020.11.30 |
---|---|
선택기 [class ^ =“span”]은 무엇을합니까? (0) | 2020.11.30 |
HTML5-크로스 브라우저 Iframe postmessage-자녀에서 부모로? (0) | 2020.11.30 |
logging.info가 콘솔에 표시되지 않지만 경고 및 오류가 발생합니다. (0) | 2020.11.30 |
Shoulda / RSpec 매처-조건부 유효성 검사 (0) | 2020.11.30 |