Python đọc tập tin cấu hình vào từ điển

Một vấn đề phổ biến với các tệp cấu hình là chúng chỉ cho phép các giá trị đơn giản như chuỗi, số nguyên, nhân đôi. Không có gì lạ khi muốn bao gồm các giá trị phức tạp hơn như danh sách hoặc từ điển trong cấu hình của bạn

Cách tiếp cận tao nhã nhất mà tôi từng thấy để thực hiện điều này trong python là sử dụng thư viện json để phân tích các giá trị. Trước tiên, tôi sẽ tải một tệp cấu hình ví dụ bằng SafeConfigParser của python. Thông thường, cấu hình của bạn sẽ nằm trong một tệp riêng biệt, tuy nhiên với mục đích của bài đăng trên blog này, tôi sẽ sử dụng một chuỗi nhiều dòng

>>> from configparser import SafeConfigParser
>>> import json
>>> config_text = """
[examples]
list_example=[1,2,3,4]
dict_example={"foo":1, "bar":2}
"""
>>> parser = SafeConfigParser()
>>> parser.read_string(config_text)
>>> parser.items("examples")
[('list_sample', '[1,2,3,4]'), ('map_example', '{"foo":1, "bar":2}')]

Danh sách các bộ dữ liệu được trả về bởi ConfigParser.items(section) có thể khó xử lý, trừ khi bạn định lặp lại tất cả các giá trị trong tệp cấu hình. Tôi thấy việc chuyển đổi danh sách thành từ điển dễ dàng hơn, đơn giản trong python

config = dict(parser.items("examples"))

Bây giờ chúng ta có một từ điển ánh xạ các khóa trong tệp cấu hình thành các giá trị của chúng, bạn có thể sử dụng json.loads(str) để chuyển đổi các giá trị từ chuỗi thành danh sách hoặc từ điển. Các hoạt động sau khi gọi json.loads trong phần tiếp theo của phiên phiên dịch của tôi là để chứng minh rằng các đối tượng này thực sự là một danh sách và từ điển python thực sự

#!/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 triển khai 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

config = configparser.ConfigParser()
config.read('db.ini')
0 ký tự. 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

________số 8_______

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

config = configparser.ConfigParser()
config.read('db.ini')

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 với
config = configparser.ConfigParser()
config.read('db.ini')
6

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

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

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

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

$ python reading_from_file.py
MySQL configuration:
Host: localhost
User: user7
Password: s$cret
Database: ydb
PostgreSQL configuration:
Host: localhost
User: user8
Password: mypwd$7
Database: testdb

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 nào được chỉ định không

#!/usr/bin/python

import configparser

config = configparser.ConfigParser()
config.read('db.ini')

sections = config.sections()
print(f'Sections: {sections}')

sections.append('sqlite')

for section in sections:

    if config.has_section(section):
      print(f'Config file has section {section}')
    else:
      print(f'Config file does not have section {section}')

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

$ python sections.py
Sections: ['mysql', 'postgresql']
Config file has section mysql
Config file has section postgresql
Config file does not have section sqlite

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

#!/usr/bin/python

import configparser

cfg_data = '''
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb
'''

config = configparser.ConfigParser()
config.read_string(cfg_data)

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

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

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ừ một từ điển bằng phương pháp

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

#!/usr/bin/python

import configparser

cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
              'passwd': 's$cret', 'db': 'ydb'}
}

config = configparser.ConfigParser()
config.read_dict(cfg_data)

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

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

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

Quảng cáo
#!/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

Làm cách nào để đọc tệp dưới dạng từ điển trong Python?

Chúng tôi có thể đọc từ điển từ một tệp theo 3 cách. .
Sử dụng json. phương thức tải (). Chuyển đổi chuỗi từ điển hợp lệ thành dạng json
sử dụng ast. phương thức literal_eval(). Hàm an toàn hơn hàm eval và cũng có thể được sử dụng để chuyển đổi xen kẽ tất cả các loại dữ liệu ngoài từ điển
Sử dụng dưa chua

Làm cách nào để đọc các giá trị từ tệp INI trong Python?

Tệp Python. # Đọc tệp và tạo nếu tệp không tồn tại config = iniFile( 'FILE. INI' ) # Nhận cấu hình "default_path". default_path # Cấu hình in (chuỗi)/đường dẫn/tên in. default_path # Tạo hoặc cập nhật cấu hình.

dict ={} trong Python là gì?

Cấu trúc bảng băm khóa/giá trị hiệu quả của Python được gọi là "dict". Nội dung của một dict có thể được viết dưới dạng một chuỗi key. cặp giá trị trong dấu ngoặc nhọn { }, e. g. chính tả = {key1. giá trị1, khóa2. giá trị2,. }. "Chính tả trống" chỉ là một cặp dấu ngoặc nhọn trống {}.

Trình cấu hình trong Python là gì?

Mô-đun configparser từ thư viện chuẩn của Python xác định chức năng đọc và ghi tệp cấu hình như được sử dụng bởi Microsoft Windows OS . Những tập tin như vậy thường có. mở rộng INI. Tệp INI bao gồm các phần, mỗi phần được dẫn đầu bởi tiêu đề [phần]. Giữa các dấu ngoặc vuông, chúng ta có thể đặt tên của phần.