怎么用脚本读取配置文件

wen 实用脚本 1

本文目录导读:

怎么用脚本读取配置文件

  1. Shell 脚本读取配置文件
  2. Python 读取配置文件
  3. Node.js 读取配置文件
  4. 通用配置文件格式示例
  5. 高级功能示例

我来介绍几种常用脚本来读取配置文件的方法,包括Shell、Python和Node.js。

Shell 脚本读取配置文件

使用source命令(简单键值对)

#!/bin/bash
# config.conf 内容示例:
# DB_HOST=localhost
# DB_PORT=3306
# DB_USER=root
# 加载配置文件
source config.conf
# 使用配置
echo "数据库地址: $DB_HOST"
echo "端口: $DB_PORT"
echo "用户: $DB_USER"

使用awk/sed解析(更精细控制)

#!/bin/bash
# 读取特定配置项
get_config() {
    local key=$1
    local file=$2
    grep "^${key}=" "$file" | cut -d'=' -f2-
}
# 使用
DB_HOST=$(get_config "DB_HOST" "config.conf")
echo "数据库地址: $DB_HOST"

支持注释和空格

#!/bin/bash
# 支持 # 注释和空行
while IFS='=' read -r key value
do
    if [[ ! "$key" =~ ^# ]] && [[ -n "$key" ]]; then
        key=$(echo "$key" | tr -d ' ')
        value=$(echo "$value" | tr -d ' ')
        eval "${key}=${value}"
    fi
done < config.conf
echo "配置项: $DB_HOST"

Python 读取配置文件

使用 configparser(标准INI格式)

import configparser
import json
# config.ini 内容示例:
# [database]
# host = localhost
# port = 3306
# user = root
config = configparser.ConfigParser()
config.read('config.ini')
# 读取配置
db_host = config['database']['host']
db_port = config.getint('database', 'port')  # 转换为整数
db_user = config['database'].get('user', 'default_user')  # 带默认值
print(f"数据库地址: {db_host}")
print(f"端口: {db_port}")

读取JSON配置文件

import json
# config.json 内容:
# {
#   "database": {
#     "host": "localhost",
#     "port": 3306
#   }
# }
with open('config.json', 'r') as f:
    config = json.load(f)
db_config = config['database']
print(f"主机: {db_config['host']}")

读取YAML配置文件(需要安装pyyaml)

import yaml
# config.yaml 内容:
# database:
#   host: localhost
#   port: 3306
with open('config.yaml', 'r') as f:
    config = yaml.safe_load(f)
print(f"数据库地址: {config['database']['host']}")

Node.js 读取配置文件

读取JSON配置

// config.json
const fs = require('fs');
// 同步读取
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
console.log(config.database.host);
// 异步读取
fs.readFile('config.json', 'utf8', (err, data) => {
    if (err) throw err;
    const config = JSON.parse(data);
    console.log(config.database.host);
});

使用 dotenv(环境变量配置)

// .env 文件
// DB_HOST=localhost
// DB_PORT=3306
require('dotenv').config();
console.log(process.env.DB_HOST);
console.log(process.env.DB_PORT);

读取INI格式配置

// 简单INI解析器
const fs = require('fs');
function parseINI(content) {
    const result = {};
    let currentSection = '';
    content.split('\n').forEach(line => {
        line = line.trim();
        if (!line || line.startsWith('#')) return;
        if (line.startsWith('[') && line.endsWith(']')) {
            currentSection = line.slice(1, -1);
            result[currentSection] = {};
        } else {
            const [key, value] = line.split('=');
            if (currentSection) {
                result[currentSection][key.trim()] = value.trim();
            } else {
                result[key.trim()] = value.trim();
            }
        }
    });
    return result;
}
const config = parseINI(fs.readFileSync('config.ini', 'utf8'));
console.log(config.database.host);

通用配置文件格式示例

示例配置文件(三种格式)

config.ini

; 数据库配置
[database]
host = localhost
port = 3306
user = root
password = 123456
; 日志配置
[log]
level = INFO
path = /var/log/app.log

config.json

{
  "database": {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "123456"
  },
  "log": {
    "level": "INFO",
    "path": "/var/log/app.log"
  }
}

config.yaml

database:
  host: localhost
  port: 3306
  user: root
  password: '123456'
log:
  level: INFO
  path: /var/log/app.log

高级功能示例

Python带默认值和类型转换

import configparser
import os
config = configparser.ConfigParser()
config.read('config.ini')
# 带默认值的读取
host = config.get('database', 'host', fallback='localhost')
port = config.getint('database', 'port', fallback=3306)
timeout = config.getfloat('database', 'timeout', fallback=30.0)
is_debug = config.getboolean('log', 'debug', fallback=False)
print(f"主机: {host}, 端口: {port}")

Shell带错误检查

#!/bin/bash
# 检查配置文件是否存在
CONFIG_FILE="config.conf"
if [ ! -f "$CONFIG_FILE" ]; then
    echo "配置文件 $CONFIG_FILE 不存在!"
    exit 1
fi
# 加载配置
source "$CONFIG_FILE"
# 检查必要配置是否存在
REQUIRED_VARS=("DB_HOST" "DB_USER" "DB_PASSWORD")
for var in "${REQUIRED_VARS[@]}"; do
    if [ -z "${!var}" ]; then
        echo "缺少必要配置: $var"
        exit 1
    fi
done

选择建议

  • 简单配置使用 INI格式(Python configparser、Shell source)
  • 复杂配置使用 JSON(Python json、Node.js JSON.parse)
  • 需要注释和层级使用 YAML(Python yaml库)
  • 环境变量使用 .env(Node.js dotenv)

根据你的具体需求和编程环境选择合适的方案!

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