python-3.x - 在 pyhocon 中是否可以在运行时包含文件
问题描述
在 pyhocon 中是否可以在运行时包含文件?
我知道如何在运行时合并树,例如
conf = ConfigFactory.parse_file(conf_file)
conf1 = ConfigFactory.parse_file(include_conf)
conf = ConfigTree.merge_configs(conf, conf1)
我想模拟 include 语句,以便在运行时评估 hocon 变量,如下面的如意代码:
conf = ConfigFactory.parse_files([conf_file, include_conf])
解决方案
可以使用字符串:
from pyhocon import ConfigFactory
# readingconf entrypoint
file = open('application.conf', mode='r')
conf_string = file.read()
file.close()
conf_string_ready = conf_string.replace("PATH_TO_CONFIG","spec.conf")
conf = ConfigFactory.parse_string(conf_string_ready)
print(conf)
application.conf 有
include "file://INCLUDE_FILE"
或者在运行时没有准备,我自己使用 python 3.65 编写了它:
#!/usr/bin/env python
import os
from pyhocon import ConfigFactory as Cf
def is_line_in_file(full_path, line):
with open(full_path) as f:
content = f.readlines()
for l in content:
if line in l:
f.close()
return True
return False
def line_prepender(filename, line, once=True):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
if is_line_in_file(filename, line) and once:
return
f.write(line.rstrip('\r\n') + '\n' + content)
def include_configs(base_path, included_paths):
for included_path in included_paths:
line_prepender(filename=base_path, line=f'include file("{included_path}")')
return Cf.parse_file(base_path)
if __name__ == "__main__":
dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")
dir_path = ''
_base_path = f'{dir_path}example.conf'
_included_files = [f'{dir_path}example1.conf', f'{dir_path}example2.conf']
_conf = include_configs(base_path=_base_path, included_paths=_included_files)
print('break point')
推荐阅读
- javascript - 网站上的问题..注册仍然出现在登录表单上
- windows-10 - 你如何为 MS Teams 制定 Windows Defender 防火墙规则?
- javascript - 过滤函数在reactjs中返回空数组
- sql-server - 死锁 - 从死锁报告中查找完整的 SQL 语句
- laravel - Laravel 获取模型可用座位
- node.js - 用 Jest 模拟模块无法正常工作
- c# - C# - Revit - 零件的长度和方向
- c# - 使用对象自己的值对数组中的对象执行更新
- awk - 使用 awk 打印不带双引号
- ios - 使用 Frida 枚举 ivars (iOS)