ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
| configparser 模块 | 内置模块,无须安装 | | --- | --- | ``` import configparser import os import pymysql class Mysql: def __init__(self): config = configparser.ConfigParser() #解决方法:当不是在根目录执行脚本时无法获取到配置文件,以下做判断 #获取可执行的py文件所在路径,缺点:手动执行时,获取的是python的安装路径,而不是可执行py文件所在的路径 run_path = os.path.dirname(os.sys.executable) #获取可执行的py文件所在路径的上一级路径,缺点:文件所在文件夹名字写死了不能更改 py_path = os.path.dirname(os.sys.path[0]) ##做个判断,避免上述缺点 if os.path.exists(py_path + "/GYL_AJEUB/config/default.conf"): config.read(py_path + "/GYL_AJEUB/config/default.conf") else: print("无法获取到配置文件") return None try: self._db = pymysql.connect(host=config.get('database', 'db_host'),user=config.get('database', 'db_user'),passwd=config.get('database', 'db_pass'),db=config.get('database', 'db_name'),charset='utf8',cursorclass=pymysql.cursors.DictCursor) except Exception as e: print("数据库连接错误:%s" %(e)) return None finally: pass ``` 报错:Python读取配置文件:ConfigParser.NoSectionError: No section 场景:在脚本目录下手动执行正常,crontab 定时任务执行报错 原因:定时执行时,configparser找不到配置文件 解决方法:上面代码注释部分