Python脚本如何读取配置文件

wen 实用脚本 1

本文目录导读:

Python脚本如何读取配置文件

  1. INI 配置文件(使用 configparser
  2. JSON 配置文件(使用 json 模块)
  3. YAML 配置文件(需要安装 PyYAML
  4. 环境变量配置(使用 ospython-dotenv
  5. 自定义配置类(打包配置)
  6. 综合示例:支持多种格式
  7. 选择建议:

Python读取配置文件有多种方式,主要取决于配置文件的格式,以下是几种常见的方法:

INI 配置文件(使用 configparser

示例配置文件 config.ini:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no

读取代码:

import configparser
# 创建配置解析器
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取配置值
server_alive = config['DEFAULT']['ServerAliveInterval']
compression = config['DEFAULT']['Compression']
bitbucket_user = config['bitbucket.org']['User']
port = config['topsecret.server.com'].getint('Port')  # 转换为整数
print(f"Server Alive Interval: {server_alive}")
print(f"Compression: {compression}")
print(f"Bitbucket User: {bitbucket_user}")
print(f"Port: {port}")

JSON 配置文件(使用 json 模块)

示例配置文件 config.json:

{
    "database": {
        "host": "localhost",
        "port": 3306,
        "user": "admin",
        "password": "secret"
    },
    "app": {
        "debug": true,
        "log_level": "INFO"
    }
}

读取代码:

import json
# 读取 JSON 配置文件
with open('config.json', 'r', encoding='utf-8') as f:
    config = json.load(f)
# 访问配置
db_host = config['database']['host']
db_port = config['database']['port']
debug_mode = config['app']['debug']
print(f"Database Host: {db_host}")
print(f"Database Port: {db_port}")
print(f"Debug Mode: {debug_mode}")

YAML 配置文件(需要安装 PyYAML

安装:

pip install pyyaml

示例配置文件 config.yaml:

server:
  host: "0.0.0.0"
  port: 8080
database:
  host: "localhost"
  port: 5432
  user: "postgres"
  password: "mypassword"
logging:
  level: "INFO"
  file: "app.log"

读取代码:

import yaml
# 读取 YAML 配置文件
with open('config.yaml', 'r') as f:
    config = yaml.safe_load(f)
# 访问配置
server_host = config['server']['host']
server_port = config['server']['port']
db_host = config['database']['host']
print(f"Server: {server_host}:{server_port}")
print(f"Database: {db_host}")

环境变量配置(使用 ospython-dotenv

使用 os.environ:

import os
# 读取环境变量
db_host = os.getenv('DB_HOST', 'localhost')  # 第二个参数是默认值
db_port = os.getenv('DB_PORT', '3306')
debug = os.getenv('DEBUG', 'False').lower() == 'true'
print(f"DB Host: {db_host}")
print(f"DB Port: {db_port}")
print(f"Debug: {debug}")

使用 .env 文件(需要安装 python-dotenv):

pip install python-dotenv

示例 .env 文件:

DB_HOST=localhost
DB_PORT=3306
DB_USER=admin
DB_PASSWORD=secret123
DEBUG=True

读取代码:

from dotenv import load_dotenv
import os
# 加载 .env 文件
load_dotenv()
# 读取配置
db_host = os.getenv('DB_HOST')
db_port = os.getenv('DB_PORT')
debug = os.getenv('DEBUG', 'False').lower() == 'true'
print(f"Database Host: {db_host}")
print(f"Database Port: {db_port}")
print(f"Debug: {debug}")

自定义配置类(打包配置)

import configparser
import json
class Config:
    def __init__(self, config_file='config.ini'):
        self.config = configparser.ConfigParser()
        self.config.read(config_file)
    def get(self, section, key, default=None):
        try:
            return self.config[section][key]
        except (KeyError, configparser.NoSectionError):
            return default
    def getint(self, section, key, default=0):
        try:
            return self.config[section].getint(key)
        except (KeyError, configparser.NoSectionError):
            return default
    def getboolean(self, section, key, default=False):
        try:
            return self.config[section].getboolean(key)
        except (KeyError, configparser.NoSectionError):
            return default
# 使用示例
config = Config('config.ini')
db_host = config.get('database', 'host', 'localhost')
debug = config.getboolean('app', 'debug', False)

综合示例:支持多种格式

import os
import json
import configparser
import yaml
def load_config(config_file):
    """自动检测配置文件格式并加载"""
    if not os.path.exists(config_file):
        raise FileNotFoundError(f"配置文件 {config_file} 不存在")
    ext = os.path.splitext(config_file)[1].lower()
    if ext == '.ini':
        config = configparser.ConfigParser()
        config.read(config_file)
        return config
    elif ext == '.json':
        with open(config_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    elif ext in ['.yaml', '.yml']:
        with open(config_file, 'r') as f:
            return yaml.safe_load(f)
    elif ext == '.env':
        from dotenv import load_dotenv
        load_dotenv(config_file)
        return os.environ
    else:
        raise ValueError(f"不支持的配置文件格式: {ext}")
# 使用示例
config = load_config('config.json')
print(config)

选择建议:

  1. 小型项目:使用 JSONINI 格式,简单易懂
  2. 大型项目:使用 YAML 格式,支持复杂数据结构
  3. 敏感信息:使用环境变量或 .env 文件,避免硬编码密码
  4. 跨平台:环境变量是最好的选择

这样可以灵活地处理各种配置需求。

抱歉,评论功能暂时关闭!