Python: 간단한 설정/구성 파일을 저장하는 방법은 무엇입니까?
난 상관 안 해JSON
,pickle
,YAML
뭐, 뭐 그런 거.
그 외의 실장은 모두 순방향으로 대응하고 있지 않기 때문에, 설정 파일이 있는 경우는, 코드에 새로운 키를 추가하고, 그 설정 파일을 로드하면, 크래쉬 할 뿐입니다.
간단하게 할 수 있는 방법이 있나요?
python 구성 파일
필요한 파일 형식에 따라 몇 가지 방법이 있습니다.
ConfigParser [.ini 형식]
다른 포맷을 사용해야 하는 특별한 이유가 없는 한 표준 컨피규레이션파서 방식을 사용합니다.
다음과 같은 파일을 작성합니다.
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')
with open('config.ini', 'w') as f:
config.write(f)
파일 형식은 매우 간단합니다.섹션은 대괄호로 둘러싸여 있습니다.
[main]
key1 = value1
key2 = value2
key3 = value3
다음과 같이 파일에서 값을 추출할 수 있습니다.
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
print(config.get('main', 'key1')) # -> "value1"
print(config.get('main', 'key2')) # -> "value2"
print(config.get('main', 'key3')) # -> "value3"
# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')
# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')
JSON [.json 형식]
JSON 데이터는 매우 복잡할 수 있으며 휴대성이 뛰어나다는 장점이 있습니다.
파일에 데이터 쓰기:
import json
config = {"key1": "value1", "key2": "value2"}
with open('config1.json', 'w') as f:
json.dump(config, f)
파일에서 데이터 읽기:
import json
with open('config.json', 'r') as f:
config = json.load(f)
#edit the data
config['key3'] = 'value3'
#write it back to the file
with open('config.json', 'w') as f:
json.dump(config, f)
YAML
이 답변에는 기본적인 YAML 예가 나와 있습니다.자세한 내용은 pyYAML 웹사이트를 참조하십시오.
ConfigParser Basic 예시
파일은 다음과 같이 로드하여 사용할 수 있습니다.
#!/usr/bin/env python
import ConfigParser
import io
# Load the configuration file
with open("config.yml") as f:
sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))
# List all contents
print("List all contents")
for section in config.sections():
print("Section: %s" % section)
for options in config.options(section):
print("x %s:::%s:::%s" % (options,
config.get(section, options),
str(type(options))))
# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous')) # Just get the value
print(config.getboolean('other', 'use_anonymous')) # You know the datatype?
출력되는 것
List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>
Print some contents
yes
True
보다시피 읽고 쓰기 쉬운 표준 데이터 형식을 사용할 수 있습니다.getboolean 및 getint 등의 메서드를 사용하면 단순한 문자열 대신 데이터 유형을 가져올 수 있습니다.
기입 설정
import os
configfile_name = "config.yaml"
# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
# Create the configuration file as it doesn't exist yet
cfgfile = open(configfile_name, 'w')
# Add content to the file
Config = ConfigParser.ConfigParser()
Config.add_section('mysql')
Config.set('mysql', 'host', 'localhost')
Config.set('mysql', 'user', 'root')
Config.set('mysql', 'passwd', 'my secret password')
Config.set('mysql', 'db', 'write-math')
Config.add_section('other')
Config.set('other',
'preprocessing_queue',
['preprocessing.scale_and_center',
'preprocessing.dot_reduction',
'preprocessing.connect_lines'])
Config.set('other', 'use_anonymous', True)
Config.write(cfgfile)
cfgfile.close()
을 낳다
[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math
[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True
XML 기본 예시
Python 커뮤니티에서 컨피규레이션파일에 전혀 사용되지 않는 것 같습니다.그러나 Python에서는 XML 해석/기입이 쉽고 많은 가능성이 있습니다.하나는 Beautiful Soup:
from BeautifulSoup import BeautifulSoup
with open("config.xml") as f:
content = f.read()
y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
print(tag)
여기서 config.xml은 다음과 같습니다.
<config>
<mysql>
<host>localhost</host>
<user>root</user>
<passwd>my secret password</passwd>
<db>write-math</db>
</mysql>
<other>
<preprocessing_queue>
<li>preprocessing.scale_and_center</li>
<li>preprocessing.dot_reduction</li>
<li>preprocessing.connect_lines</li>
</preprocessing_queue>
<use_anonymous value="true" />
</other>
</config>
INI 파일등의 설정을 보관 유지하는 경우는, 텍스트파일로부터 키 값의 페어를 로드해, 파일에 간단하게 기입할 수 있는 config parser 의 사용을 검토해 주세요.
INI 파일의 형식은 다음과 같습니다.
[Section]
key = value
key with spaces = somevalue
간단한 설정 파일에는 JSON 파일(예: conf.json:
{
"version": 1,
"bind": {
"address": "127.0.0.1",
"port": 8080
},
"data": {
"a": [1, 2, 3],
"b": 2.5
}
}
다음으로 다음 커스텀 JSON 구성 리더를 만듭니다.
import json
class Dict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class Config(object):
@staticmethod
def __load__(data):
if type(data) is dict:
return Config.load_dict(data)
elif type(data) is list:
return Config.load_list(data)
else:
return data
@staticmethod
def load_dict(data: dict):
result = Dict()
for key, value in data.items():
result[key] = Config.__load__(value)
return result
@staticmethod
def load_list(data: list):
result = [Config.__load__(item) for item in data]
return result
@staticmethod
def load_json(path: str):
with open(path, "r") as f:
result = Config.__load__(json.loads(f.read()))
return result
마지막으로 다음 명령을 사용하여 로드합니다.
conf = Configuration.load_json('conf.json')
이것으로, 닷 「」를 사용해 설정에 액세스 할 수 있습니다.예:
print(conf.version)
print(conf.bind.address)
print(conf.bind.port)
print(conf.data.a)
print(conf.data.b)
사전을 저장하고 로드합니다.임의의 키, 값 및 임의의 수의 키, 값 쌍이 있습니다.
ReadSettings를 사용해 보십시오.
from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"
저도 같은 문제에 직면했습니다만, 컨피규레이션파일이 존재하지 않는 경우를 대비해 하드코드필드에서 컨피규레이션 변수를 읽고 싶습니다.
「 」 「 」:
import json
class Configurator:
def __init__(self):
# Hard coded values if config file doesn't exist
self.alpha: int = 42
self.bravo: float = 3.14
self.charlie: str = "8.8.8.8"
self.delta: list = ["Lorem", "ipsum", "dolor", "sit", "amet"]
self.echo: dict = {"Winter": "is coming"}
def read_config_file(self, config_file_name: str = "config.json"):
try:
with open(config_file_name) as conf_file:
for k, v in json.loads(conf_file.read()).items():
setattr(self, k, v)
except Exception as e:
print(f"Error was detected while reading {config_file_name}: {str(e)}. Hard coded values will be applied")
def save_config_file(self, config_file_name: str = "config.json"):
try:
conf_items = {k: v for k, v in vars(self).items() if isinstance(v, (int, float, str, list, dict))}
with open(config_file_name, "w") as conf_file:
json.dump(conf_items, conf_file, sort_keys=False, indent=2)
except Exception as e:
print(f"Error was detected while saving {config_file_name}: {str(e)}")
from configurator import Configurator
if __name__ == '__main__':
conf = Configurator()
# Read config (values from file or hard coded values if file doesn't exist)
conf.read_config_file()
# Using values from config
a = conf.alpha
# Changing values in config
conf.bravo += 1
# Save changed config to file
conf.save_config_file()
컨피규레이션파일이 존재하지 않는 경우는, 최초의 conf 콜 후에 표시됩니다.save_config_file save save그 후 config.json을 변경하면 다음 번에는 파일의 변수가 하드코딩된 변수를 "비트"해야 합니다.
코드가 좀 해킹되었으니 사용하기 전에 테스트해 보세요.
cfg4py를 사용해 보겠습니다.
- 계층형 설계, 다중 환경 지원, 개발 설정과 운영 사이트 설정을 혼동하지 마십시오.
- 코드 완성Cfg4py는 yaml을 python 클래스로 변환하고 코드를 입력하는 동안 코드 완성을 사용할 수 있습니다.
- 더 많은..
면책사항: 이 모듈의 작성자입니다.
언급URL : https://stackoverflow.com/questions/19078170/python-how-would-you-save-a-simple-settings-config-file
'programing' 카테고리의 다른 글
Moment.js 와 ReactJS (ES6) (0) | 2023.02.26 |
---|---|
Play 2.2 라이브러리로 밀봉된 특성을 위한 노이즈 프리 JSON 형식 (0) | 2023.02.26 |
WordPress에서 현재 사용자의 역할을 아는 방법 (0) | 2023.02.26 |
jQuery ajax 호출에 여러 파라미터 전달 (0) | 2023.02.26 |
jq: 문자열로 어레이를 인덱싱할 수 없습니다. (0) | 2023.02.26 |