Python:如何在脚本运行时通过配置文件修改参数?
Python脚本运行时动态加载配置参数的最佳方案
针对运行时修改配置文件后无法自动加载的问题,以下是几种实用的解决方案,按场景优先级排序:
1. 定时轮询配置文件(无额外依赖,适合简单场景)
核心思路是在后台启动一个线程,定期检查配置文件的修改时间或内容哈希,当检测到变化时重新加载配置。这种方法不需要额外安装库,实现简单。
示例代码(以YAML配置为例):
import yaml import os import time import threading from typing import Dict config: Dict = {} last_modified_time = 0 def load_config(): global config, last_modified_time with open("config.yaml", "r") as f: config = yaml.safe_load(f) last_modified_time = os.path.getmtime("config.yaml") def watch_config(): while True: current_modified = os.path.getmtime("config.yaml") if current_modified != last_modified_time: load_config() print("配置已更新") time.sleep(2) # 每隔2秒检查一次 # 初始化加载配置 load_config() # 启动后台监听线程 threading.Thread(target=watch_config, daemon=True).start() # 主逻辑示例 while True: print(f"当前参数值: {config.get('target_param')}") time.sleep(1)
2. 监听文件系统变化(实时性好,需额外依赖)
使用watchdog库监听配置文件的修改事件,一旦文件被修改立即触发重新加载,比定时轮询更高效,实时性更强。
先安装依赖:
pip install watchdog
示例代码:
import yaml import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from typing import Dict config: Dict = {} class ConfigFileHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory and event.src_path == "config.yaml": global config try: with open("config.yaml", "r") as f: config = yaml.safe_load(f) print("配置已更新") except Exception as e: print(f"配置加载失败: {e}") def load_config(): global config with open("config.yaml", "r") as f: config = yaml.safe_load(f) # 初始化加载 load_config() # 启动文件监听 event_handler = ConfigFileHandler() observer = Observer() observer.schedule(event_handler, path=".", recursive=False) observer.start() # 主逻辑示例 try: while True: print(f"当前参数值: {config.get('target_param')}") time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
3. 使用配置中心(适合分布式/多实例场景)
如果你的脚本是分布式系统的一部分,或者需要多实例共享配置,可以使用etcd、Consul这类配置中心服务。客户端可以监听配置中心的键值变化,实时同步最新配置,避免直接操作本地文件。
注意事项
- 加载配置时要添加异常处理(比如文件半写时的格式错误),保证脚本稳定性。
- 若配置涉及多线程读写,需加
threading.Lock()避免竞态条件。
内容的提问来源于stack exchange,提问作者Chucha Cuta
相关产品推荐
相关产品推荐

