Sử dụng ConfigParser trong Python để xử lý file cấu hình

Module configparser trong Python được dùng để đọc và ghi các tệp cấu hình có định dạng tương tự như file .ini trên Windows. Cấu trúc này bao gồm nhiều section (mục), mỗi section chứa các cặp key-value. Việc sử dụng file cấu hình giúp tách biệt tham số khỏi mã nguồn, tăng tính linh hoạt cho ứng dụng.

Ví dụ về một file cấu hình MySQL:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

!includedir /etc/my.cnf.d

1. Ghi file cấu hình

Để tạo mới một file cấu hình bằng Python:

import configparser

cfg = configparser.ConfigParser()

# Thiết lập section DEFAULT
cfg["DEFAULT"] = {
    'server_host': "DNS01",
    'server_ip': "0.0.0.0",
    'server_conf': "/etc/dns/name.conf"
}

# Thêm section 'user'
cfg["user"] = {}
cfg["user"]["name"] = 'root'

# Thêm section 'pass' và gán giá trị
auth_section = cfg["pass"]
auth_section["password"] = "123456"
auth_section["pass_key"] = "/root/.ssh/key.pub"

# Cập nhật thêm key vào DEFAULT
cfg['DEFAULT']["server_socket"] = "/lib/dns.sock"

# Ghi ra file
with open("named.conf", "w") as f:
    cfg.write(f)

Kết quả file named.conf:

[DEFAULT]
server_host = DNS01
server_ip = 0.0.0.0
server_conf = /etc/dns/name.conf
server_socket = /lib/dns.sock

[user]
name = root

[pass]
password = 123456
pass_key = /root/.ssh/key.pub

2. Đọc file cấu hình

Đọc và truy xuất thông tin từ file cấu hình:

import configparser

parser = configparser.ConfigParser()
parser.read("named.conf")

# Liệt kê tất cả các section (không bao gồm DEFAULT)
print(parser.sections())

# Truy cập giá trị trong section DEFAULT
if 'DEFAULT' in parser:
    print(parser['DEFAULT']["server_ip"])

# Duyệt qua tất cả các section (kể cả DEFAULT)
for section_name in parser:
    print(section_name)

3. Thao tác sửa đổi file cấu hình

Thực hiện các thao tác CRUD (tạo, đọc, cập nhật, xóa) trên file cấu hình:

import configparser

cfg_parser = configparser.ConfigParser()
cfg_parser.read("i.cfg")

# --- Đọc ---
# Lấy danh sách section
sections = cfg_parser.sections()
print(sections)

# Lấy danh sách key trong một section
keys = cfg_parser.options("section2")
print(keys)

# Lấy giá trị (có thể chuyển kiểu, ví dụ int)
# value = cfg_parser.getint("section2", "k1")

# --- Xóa ---
# Xóa toàn bộ section
# cfg_parser.remove_section("section1")
# Xóa một key trong section
# cfg_parser.remove_option("section2", "k1")

# --- Thêm ---
if not cfg_parser.has_section("mysql"):
    cfg_parser.add_section("mysql")

# Thêm hoặc cập nhật key-value
cfg_parser.set("mysql", "path", "/opt/data")

# --- Cập nhật ---
# set() tự động ghi đè nếu key đã tồn tại
cfg_parser.set("mysql", "path", "/opt/program/data")

# Lưu thay đổi vào file
with open("i.cfg", "w") as f:
    cfg_parser.write(f)

Thẻ: python configparser ini-file

Đăng vào ngày 22 tháng 5 lúc 16:53