Python-config 配置实例

情况Ⅰ:直接操作(不涉及文件读取,问题对象需要的代码较少时使用)

解说:

  • 变量stringEg的头部[configSection]为Section的名称,在调用时需要用到;

  • 等号左边最终被解析为键(key),右边被解析为值(value),形成键值对(key-value)

脚本config.py内容

import configparser
# config learn step 1(变量定义)
param = {}
stringEg ="""
[configSection]
SPATIAL_RAW_ROOT = data/t/
SPATIAL_PROCESSED_ROOT = data/hist2tscript-patch/
TCGA_RAW_ROOT = data/TCGA/
TCGA_PROCESSED_ROOT = data/TCGA-patch/
"""
# config learn step 2
config = configparser.ConfigParser()
# config learn step 3
config.read_string(stringEg)
# config learn step 4
param = config["configSection"]
# config learn step 5
print(list(config["configSection"].keys()))
print(param.get("SPATIAL_RAW_ROOT"))
print(param.get("spatial_raw_root"))
# config learn step 6 (key-value(default), fallback value)
# 即:获取param中的键par1对应的值,如果不存在,则获取备选值par2
print(param.get("spatial_raw_root", "data/hist2tscript/"))

情况Ⅱ:用.cfg文件外部操作(涉及文件读取,工程项目较大时使用,可以方便修改重要参数)

文件 FilePath.cfg 内容

解说:

  • 等号左边最终被解析为键(key),右边被解析为值(value),形成键值对(key-value)

  • 文件FilePath.cfg内部,不需要写入section的名称,代码中会指定名称;

SPATIAL_RAW_ROOT = data/t/
SPATIAL_PROCESSED_ROOT = data/hist2tscript-patch/
TCGA_RAW_ROOT = data/TCGA/
TCGA_PROCESSED_ROOT = data/TCGA-patch/

脚本config.py内容

import os
import configparser
import types
# config learn step 1
param = {}
FILENAME = None
# FilePath.cfg must be put into the same directory as config.py
for filename in ["FilePath.cfg",
".FilePath.cfg",
os.path.expanduser("~/FilePath.cfg"),
os.path.expanduser("~/.FilePath.cfg")]:
if os.path.isfile(filename):
FILENAME = filename
# config learn step 2
config = configparser.ConfigParser()
with open(filename, "r") as f:
# config learn step 3
config.read_string("[configSection]\n" + f.read())
# config learn step 4
param = config["configSection"]
print(list(config["configSection"].keys()))
print(param.get("SPATIAL_RAW_ROOT"))
print(param.get("spatial_raw_root"))
# config learn step 5
print(param.get("spatial_raw_root", "data/hist2tscript/"))
break
config = types.SimpleNamespace(FILENAME = FILENAME,
# if the key exists, return default value; else return the new value determined by the second parameter(this parameter also is called fallback value)
SPATIAL_RAW_ROOT = param.get("spatial_raw_root", "data/hist2tscript/"),
SPATIAL_PROCESSED_ROOT = param.get("spatial_processed_root","data/hist2tscript-patch/"),
TCGA_RAW_ROOT = param.get("tcga_raw_root", "data/TCGA/"),
TCGA_PROCESSED_ROOT = param.get("tcga_processed_root","data/TCGA-patch/"))

参考资料

官方文档