[python]从环境变量和配置文件中获取配置参数

简介: [python]从环境变量和配置文件中获取配置参数

前言

从环境变量和配置文件中获取配置参数,相关库:

  • python-dotenv:第三方库,需要使用pip安装
  • configparser:标准库

示例代码

  • test.ini
[mysql]
host = "192.168.0.10"
port = 3306
user = "root"
password = "123456"
[postgresql]
host = "192.168.0.11"
port = 5432
user = "postgres"
password = "123456"
  • demo.py
from configparser import ConfigParser, NoSectionError, NoOptionError
from dotenv import load_dotenv
import os
# 如果存在环境变量的文件,则加载配置到环境变量
if os.path.exists("settings.env"):
    load_dotenv("settings.env")
os_env = os.environ
def read_config(filename: str) -> ConfigParser:
    """
    从文件中读取配置信息
    Parameters
    ----------
    filename : str, 配置文件 
    """
    # 实例化对象
    config = ConfigParser()
    if not os.path.exists(filename):
        raise FileNotFoundError(f"配置文件 {filename} 不存在")
    config.read(filename, encoding="utf-8")
    return config
def get_config(config: ConfigParser, section: str, key: str):
    """
    根据指定section和key获取value
    Parameters
    ----------
    config:  ConfigParser(), 配置实例对象
    section: str, 配置文件中的区域
    key:     str, 配置的参数名
    """
    # 优先从环境变量中获取配置参数, 没有的话再从配置文件中获取
    value = os_env.get(key, "")
    if not value:
        try:
            value = config.get(section, key)
        except (NoOptionError, NoSectionError):
            # 没有的话就返回None
            value = None
    return value
if __name__ == '__main__':
    config = read_config("test.ini")
    print(get_config(config, "mysql", "host"))
相关文章
|
3月前
|
存储 数据库连接 API
Python环境变量在开发和运行Python应用程序时起着重要的作用
Python环境变量在开发和运行Python应用程序时起着重要的作用
124 15
|
3月前
|
Unix Linux Python
在Python中,删除环境变量
在Python中,删除环境变量
199 8
|
3月前
|
存储 JSON 数据格式
Python环境变量
Python环境变量
60 5
|
4月前
|
PyTorch Linux 算法框架/工具
pytorch学习一:Anaconda下载、安装、配置环境变量。anaconda创建多版本python环境。安装 pytorch。
这篇文章是关于如何使用Anaconda进行Python环境管理,包括下载、安装、配置环境变量、创建多版本Python环境、安装PyTorch以及使用Jupyter Notebook的详细指南。
463 1
pytorch学习一:Anaconda下载、安装、配置环境变量。anaconda创建多版本python环境。安装 pytorch。
|
3月前
|
安全 网络安全 数据安全/隐私保护
|
11天前
|
安全 Linux 网络安全
利用Python脚本自动备份网络设备配置
通过本文的介绍,我们了解了如何利用Python脚本自动备份网络设备配置。该脚本使用 `paramiko`库通过SSH连接到设备,获取并保存配置文件。通过定时任务调度,可以实现定期自动备份,确保网络设备配置的安全和可用。希望这些内容能够帮助你在实际工作中实现网络设备的自动化备份。
37 14
|
2月前
|
分布式计算 MaxCompute 对象存储
|
1月前
|
人工智能 编译器 Python
python已经安装有其他用途如何用hbuilerx配置环境-附带实例demo-python开发入门之hbuilderx编译器如何配置python环境—hbuilderx配置python环境优雅草央千澈
python已经安装有其他用途如何用hbuilerx配置环境-附带实例demo-python开发入门之hbuilderx编译器如何配置python环境—hbuilderx配置python环境优雅草央千澈
36 0
python已经安装有其他用途如何用hbuilerx配置环境-附带实例demo-python开发入门之hbuilderx编译器如何配置python环境—hbuilderx配置python环境优雅草央千澈
|
3月前
|
JSON Shell Linux
配置Python的环境变量可
配置Python的环境变量
307 4
|
3月前
|
存储 JSON API
如何自定义Python环境变量?
如何自定义Python环境变量?
64 3

热门文章

最新文章