影刀RPA 配置文件管理:ini、yaml、json配置读写

发布时间:2026/7/25 6:19:53
影刀RPA 配置文件管理:ini、yaml、json配置读写 影刀RPA 配置文件管理ini、yaml、json配置读写作者林焱什么情况用你的影刀流程需要连接不同环境的数据库开发/测试/生产每次切换都要改代码流程的采集参数超时时间、重试次数、采集页数经常变每次都改流程太麻烦多个流程共享同一套配置数据库连接、API密钥、邮箱账号配置文件管理是让流程灵活可维护的关键。把可变参数从代码中抽出来放到配置文件中修改配置不需要改流程代码。影刀RPA的Python代码块可以读写多种配置文件格式。本文讲清楚三种主流配置格式ini、yaml、json的读写方法、什么时候用哪种、怎么实现多环境配置切换。怎么做一、三种配置格式对比格式扩展名优点缺点适用场景JSON.jsonPython内置支持通用性强不支持注释语法严格API配置、数据交换YAML.yaml/.yml支持注释可读性好支持复杂数据需要安装PyYAML复杂配置文件拼多多店群自动化上架方案| INI | .ini | 简单支持分节 | 只支持简单键值对 | 简单配置 |二、JSON配置文件importjsonimportos# 写入JSON配置 defwrite_json_config(config,filepath):写入JSON配置文件withopen(filepath,w,encodingutf-8)asf:json.dump(config,f,ensure_asciiFalse,indent2)print(f配置已保存到{filepath})# 读取JSON配置 defread_json_config(filepath):读取JSON配置文件ifnotos.path.exists(filepath):print(f配置文件不存在:{filepath})return{}withopen(filepath,r,encodingutf-8)asf:returnjson.load(f)# 实际配置示例 config{database:{host:192.168.1.100,port:3306,username:root,password:password123,database:production},scrape:{max_pages:50,timeout:30,retry:3,delay:[1,3]},email:{smtp_server:smtp.example.com,smtp_port:465,sender:botexample.com,password:email_password},output:{dir:D:/output,filename_format:report_{date}.xlsx}}# 写入配置write_json_config(config,config.json)# 读取配置loaded_configread_json_config(config.json)# 使用配置db_hostloaded_config[database][host]max_pagesloaded_config[scrape][max_pages]print(f数据库地址:{db_host})print(f最大页数:{max_pages})三、YAML配置文件# 需要先安装PyYAML: pip install pyyamlimportyamlimportos# 写入YAML配置 defwrite_yaml_config(config,filepath):写入YAML配置文件withopen(filepath,w,encodingutf-8)asf:yaml.dump(config,f,allow_unicodeTrue,default_flow_styleFalse,sort_keysFalse)print(f配置已保存到{filepath})# 读取YAML配置 defread_yaml_config(filepath):读取YAML配置文件ifnotos.path.exists(filepath):print(f配置文件不存在:{filepath})return{}withopen(filepath,r,encodingutf-8)asf:returnyaml.safe_load(f)# YAML配置文件示例可读性比JSON好很多 yaml_content # 数据库配置 database: host: 192.168.1.100 port: 3306 username: root password: password123 database: production # 采集配置 scrape: max_pages: 50 # 最大采集页数 timeout: 30 # 超时秒数 retry: 3 # 重试次数 delay: [1, 3] # 随机延时范围 # 邮件配置 email: smtp_server: smtp.example.com smtp_port: 465 sender: botexample.com password: email_password # 输出配置 output: dir: D:/output filename_format: report_{date}.xlsx # 写入withopen(config.yaml,w,encodingutf-8)asf:f.write(yaml_content)# 读取configread_yaml_config(config.yaml)print(config[database][host])print(config[scrape][max_pages])四、INI配置文件importconfigparserimportos# 写入INI配置 defwrite_ini_config(config_dict,filepath):写入INI配置文件configconfigparser.ConfigParser()forsection,valuesinconfig_dict.items():config[section]valueswithopen(filepath,w,encodingutf-8)asf:config.write(f)print(f配置已保存到{filepath})# 读取INI配置 defread_ini_config(filepath):读取INI配置文件configconfigparser.ConfigParser()ifnotos.path.exists(filepath):print(f配置文件不存在:{filepath})return{}config.read(filepath,encodingutf-8)# 转换为普通字典result{}forsectioninconfig.sections():result[section]dict(config.items(section))returnresult# INI文件示例 [database] host 192.168.1.100 port 3306 username root password password123 database production [scrape] max_pages 50 timeout 30 retry 3 [email] smtp_server smtp.example.com smtp_port 465 sender botexample.com # 写入config_dict{database:{host:192.168.1.100,port:3306,username:root,},scrape:{max_pages:50,timeout:30,}}write_ini_config(config_dict,config.ini)# 读取configread_ini_config(config.ini)# 注意INI的值都是字符串需要自己转换类型max_pagesint(config.get(scrape,{}).get(max_pages,10))五、配置管理器类importjsonimportosfromdatetimeimportdatetimeclassConfigManager:通用配置管理器def__init__(self,config_fileconfig.json):self.config_fileconfig_file self.config{}self.default_config{}# 默认配置self.load()defset_defaults(self,defaults):设置默认配置self.default_configdefaults# 合并用户配置覆盖默认配置self.configself._deep_merge(defaults,self.config)def_deep_merge(self,base,override):深度合并两个字典resultbase.copy()forkey,valueinoverride.items():ifkeyinresultandisinstance(result[key],dict)andisinstance(value,dict):result[key]self._deep_merge(result[key],value)else:result[key]valuereturnresultdefget(self,*keys,defaultNone):获取嵌套配置值valueself.configforkeyinkeys:ifisinstance(value,dict):valuevalue.get(key)else:returndefaultifvalueisNone:returndefaultreturnvaluedefset(self,*keys_and_value):设置配置值iflen(keys_and_value)2:return*keys,valuekeys_and_value configself.configforkeyinkeys[:-1]:ifkeynotinconfig:config[key]{}configconfig[key]config[keys[-1]]valuedefload(self):加载配置ifos.path.exists(self.config_file):withopen(self.config_file,r,encodingutf-8)asf:self.configjson.load(f)else:self.config{}defsave(self):保存配置withopen(self.config_file,w,encodingutf-8)asf:json.dump(self.config,f,ensure_asciiFalse,indent2)defupdate_and_save(self,updates):更新配置并保存self.configself._deep_merge(self.config,updates)self.save()# 使用示例managerConfigManager(config.json)# 设置默认值manager.set_defaults({scrape:{max_pages:10,timeout:30,retry:3,delay:[1,3]},output:{dir:D:/output,format:xlsx}})# 读取配置max_pagesmanager.get(scrape,max_pages,default10)timeoutmanager.get(scrape,timeout,default30)output_dirmanager.get(output,dir,default./output)print(f最大页数:{max_pages})print(f超时:{timeout}秒)print(f输出目录:{output_dir})# 修改配置manager.set(scrape,max_pages,100)manager.save()六、多环境配置importjsonimportosclassEnvironmentConfig:多环境配置管理def__init__(self,config_dirconfig):self.config_dirconfig_dir self.environmentself._detect_environment()self.configself._load_config()def_detect_environment(self):检测当前环境# 方式1通过环境变量envos.environ.get(RPA_ENV,production)returnenvdef_load_config(self):加载配置先加载基础配置再用环境配置覆盖# 基础配置base_configself._load_json(base.json)# 环境配置env_configself._load_json(f{self.environment}.json)# 合并returnself._deep_merge(base_config,env_config)def_load_json(self,filename):加载JSON文件filepathos.path.join(self.config_dir,filename)ifos.path.exists(filepath):withopen(filepath,r,encodingutf-8)asf:returnjson.load(f)return{}def_deep_merge(self,base,override):深度合并resultbase.copy()forkey,valueinoverride.items():ifkeyinresultandisinstance(result[key],dict)andisinstance(value,dict):result[key]self._deep_merge(result[key],value)else:result[key]valuereturnresultdefget(self,*keys,defaultNone):获取配置值valueself.configforkeyinkeys:ifisinstance(value,dict):valuevalue.get(key)else:returndefaultifvalueisNone:returndefaultreturnvalue# 文件结构# config/# base.json ← 所有环境共享的基础配置# development.json ← 开发环境覆盖配置# production.json ← 生产环境覆盖配置# base.json: { app: {name: 数据采集系统}, scrape: {retry: 3, delay: [1, 3]}, output: {dir: D:/output} } # development.json: { database: {host: localhost, port: 3306, name: dev_db}, scrape: {max_pages: 5, timeout: 10} } # production.json: { database: {host: 192.168.1.100, port: 3306, name: prod_db}, scrape: {max_pages: 100, timeout: 30} } # 使用configEnvironmentConfig(config)db_hostconfig.get(database,host,defaultlocalhost)max_pagesconfig.get(scrape,max_pages,default10)有什么坑坑1配置文件中的密码明文存储现象配置文件中的数据库密码、API密钥都是明文不安全。解决敏感信息不要硬编码在配置文件中。使用环境变量importos db_passwordos.environ.get(DB_PASSWORD,)# 或者在配置文件中引用环境变量# config.json: {password: ${DB_PASSWORD}}# 读取后替换passwordconfig.get(password,)ifpassword.startswith(${)andpassword.endswith(}):env_keypassword[2:-1]passwordos.environ.get(env_key,)或者使用加密存储读取时解密。坑2INI配置值都是字符串TEMU店群如何管理运营现象INI文件中写port 3306读取后是字符串3306而不是整数3306。原因INI格式不支持数据类型所有值都是字符串。解决读取后手动转换类型。或者使用JSON/YAML格式它们支持原生数据类型。如果必须用INI写一个类型转换辅助函数。坑3YAML安装问题现象import yaml报ModuleNotFoundError。解决YAML不是Python标准库需要安装pip install pyyaml。在影刀RPA的Python环境中安装包参考影刀的包管理功能或用Python代码块的pip安装。坑4配置文件被修改后流程不重启不生效现象修改了配置文件但流程运行时用的还是旧配置。原因配置只在流程启动时加载一次后续修改不会自动重新加载。解决如果需要动态加载在关键步骤前重新读取配置文件。或者实现配置文件监控——检测到配置文件修改时间变化时自动重新加载。但对于大部分RPA场景流程启动时加载一次就够了。坑5配置文件路径在打包后找不到现象开发时配置文件在相对路径config.json流程部署到其他电脑后找不到文件。解决用绝对路径或基于流程文件的相对路径importos# 获取当前Python文件所在目录base_diros.path.dirname(os.path.abspath(__file__))config_pathos.path.join(base_dir,config.json)# 或者在影刀中使用工作目录# config_path os.path.join(yd_var[work_dir], config.json)在配置管理器中设置默认的配置文件路径通过参数允许覆盖。