Trình cấu hình Python để dict

Có thể lưu trữ từ điển đa chiều [sâu 3] bằng cách sử dụng 'configparser' của Python bằng cách sử dụng chỉ định không?

Như bạn có thể thấy, các giá trị chuỗi không được trích dẫn. Tuy nhiên, đối với tôi nó có vẻ khập khiễng. IMO một chuỗi phải nằm giữa dấu ngoặc kép hoặc dấu nháy đơn. Với dấu ngoặc kép, bạn cũng có thể thêm các ký tự khoảng trắng vào đầu hoặc cuối chuỗi. Vì vậy, tôi thích viết này

[OPTIONS]
name = "Jabba"

Nhưng bây giờ trích dẫn trở thành một phần của chuỗi. Nếu bạn đọc nó bằng configparser, giá trị của

#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences["preferences.ini"]
d = prefs.as_dict[]
pprint[d]
0 là
#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences["preferences.ini"]
d = prefs.as_dict[]
pprint[d]
1 thay vì
[OPTIONS]
name = "Jabba"
0

Giải pháp
Khi sử dụng configparser, nó sẽ tạo một đối tượng giống như dict. Tôi thích làm việc với từ điển bình thường hơn. Vì vậy, đầu tiên tôi đọc tệp

#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences["preferences.ini"]
d = prefs.as_dict[]
pprint[d]
2, sau đó chuyển đổi đối tượng configparser thành dict và cuối cùng tôi xóa dấu ngoặc kép [hoặc dấu nháy đơn] khỏi giá trị chuỗi. Đây là giải pháp của tôi.

sở thích. ban đầu

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'

ví dụ. py

#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences["preferences.ini"]
d = prefs.as_dict[]
pprint[d]

sở thích. py

import sys
import configparser
import json
from pprint import pprint

def remove_quotes[original]:
    d = original.copy[]
    for key, value in d.items[]:
        if isinstance[value, str]:
            s = d[key]
            if s.startswith[['"', "'"]]:
                s = s[1:]
            if s.endswith[['"', "'"]]:
                s = s[:-1]
            d[key] = s
            # print[f"string found: {s}"]
        if isinstance[value, dict]:
            d[key] = remove_quotes[value]
    #
    return d

class Preferences:
    def __init__[self, preferences_ini]:
        self.preferences_ini = preferences_ini

        self.config = configparser.ConfigParser[]
        self.config.read[preferences_ini]

        self.d = self.to_dict[self.config._sections]

    def as_dict[self]:
        return self.d

    def to_dict[self, config]:
        """
        Nested OrderedDict to normal dict.
        Also, remove the annoying quotes [apostrophes] from around string values.
        """
        d = json.loads[json.dumps[config]]
        d = remove_quotes[d]
        return d

Dòng

[OPTIONS]
name = "Jabba"
2 chịu trách nhiệm loại bỏ các trích dẫn. Bình luận/bỏ ghi chú dòng này để thấy sự khác biệt

#!/usr/bin/python

import configparser

config = configparser.ConfigParser[]
config.read['db.ini']

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print['MySQL configuration:']

print[f'Host: {host}']
print[f'User: {user}']
print[f'Password: {passwd}']
print[f'Database: {db}']

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print['PostgreSQL configuration:']

print[f'Host: {host2}']
print[f'User: {user2}']
print[f'Password: {passwd2}']
print[f'Database: {db2}']
8 là một lớp Python thực hiện ngôn ngữ cấu hình cơ bản cho các chương trình Python. Nó cung cấp một cấu trúc tương tự như các tệp Microsoft Windows INI.
#!/usr/bin/python

import configparser

config = configparser.ConfigParser[]
config.read['db.ini']

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print['MySQL configuration:']

print[f'Host: {host}']
print[f'User: {user}']
print[f'Password: {passwd}']
print[f'Database: {db}']

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print['PostgreSQL configuration:']

print[f'Host: {host2}']
print[f'User: {user2}']
print[f'Password: {passwd2}']
print[f'Database: {db2}']
8 cho phép viết các chương trình Python mà người dùng cuối có thể tùy chỉnh dễ dàng

Tệp cấu hình bao gồm các phần theo sau là các cặp tùy chọn khóa/giá trị. Tên phần được phân cách bằng ký tự

config = configparser.ConfigParser[]
config.read['db.ini']
0. Các cặp được phân tách bằng
config = configparser.ConfigParser[]
config.read['db.ini']
1 hoặc
config = configparser.ConfigParser[]
config.read['db.ini']
2. Nhận xét bắt đầu bằng
config = configparser.ConfigParser[]
config.read['db.ini']
3 hoặc bằng
config = configparser.ConfigParser[]
config.read['db.ini']
4

Python ConfigParser đọc tệp

Trong ví dụ đầu tiên, chúng tôi đọc dữ liệu cấu hình từ một tệp

[OPTIONS]
name = "Jabba"
3

Chúng tôi có hai phần dữ liệu cấu hình

#!/usr/bin/python

import configparser

config = configparser.ConfigParser[]
config.read['db.ini']

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print['MySQL configuration:']

print[f'Host: {host}']
print[f'User: {user}']
print[f'Password: {passwd}']
print[f'Database: {db}']

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print['PostgreSQL configuration:']

print[f'Host: {host2}']
print[f'User: {user2}']
print[f'Password: {passwd2}']
print[f'Database: {db2}']

Ví dụ đọc dữ liệu cấu hình cho MySQL và PostgreSQL

________số 8

Chúng tôi bắt đầu

#!/usr/bin/python

import configparser

config = configparser.ConfigParser[]
config.read['db.ini']

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print['MySQL configuration:']

print[f'Host: {host}']
print[f'User: {user}']
print[f'Password: {passwd}']
print[f'Database: {db}']

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print['PostgreSQL configuration:']

print[f'Host: {host2}']
print[f'User: {user2}']
print[f'Password: {passwd2}']
print[f'Database: {db2}']
8 và đọc tệp bằng
config = configparser.ConfigParser[]
config.read['db.ini']
6

[OPTIONS]
name = "Jabba"
8

Chúng tôi truy cập các tùy chọn từ phần mysql

[OPTIONS]
name = "Jabba"
9

Chúng tôi truy cập các tùy chọn từ phần postgresql

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
0

Dữ liệu cấu hình được tổ chức thành các phần.

config = configparser.ConfigParser[]
config.read['db.ini']
7 đọc tất cả các phần và
config = configparser.ConfigParser[]
config.read['db.ini']
8 kiểm tra xem có phần được chỉ định không

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
3

Ví dụ hoạt động với các phần

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
4

Python ConfigParser đọc từ chuỗi

Kể từ Python 3. 2, chúng ta có thể đọc dữ liệu cấu hình từ một chuỗi bằng phương thức

config = configparser.ConfigParser[]
config.read['db.ini']
9

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
6

Ví dụ đọc cấu hình từ một chuỗi

Kể từ Python 3. 2, chúng ta có thể đọc dữ liệu cấu hình từ từ điển bằng phương thức

[OPTIONS]
name = "Jabba"
80

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'
8

Ví dụ đọc cấu hình từ từ điển Python

#!/usr/bin/python

import configparser

config = configparser.ConfigParser[]
config.read['db.ini']

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print['MySQL configuration:']

print[f'Host: {host}']
print[f'User: {user}']
print[f'Password: {passwd}']
print[f'Database: {db}']

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print['PostgreSQL configuration:']

print[f'Host: {host2}']
print[f'User: {user2}']
print[f'Password: {passwd2}']
print[f'Database: {db2}']
0

Khóa là tên phần, giá trị là từ điển có khóa và giá trị có trong phần

Chủ Đề