【问题标题】:Why am I getting a KeyError when reading an ini file with Python's configparser?为什么在使用 Python 的 configparser 读取 ini 文件时出现 KeyError?
【发布时间】:2022-01-01 02:04:36
【问题描述】:

我想用 Python 连接到数据库。 我的代码:

from configparser import ConfigParser
import pymysql as mysql

class DatabaseG:
    def __init__(self):
        config = ConfigParser()
        config.read("config.ini")
        self.connection = mysql.connect(
                user=config["books"]["user"],
                passwd=config["books"]["password"],
                host=config["books"]["host"],
                db=config["books"]["database"],
        )
        self.cursor = self.connection.cursor()
        query = """
                CREATE TABLE BOOKS (book_url TEXT, book_id)
                """

        self.cursor.execute(query)

db = DatabaseG()

我的 config.ini 如下所示:

[books]
user=myuser
password=mypass
host=blabla.cz
database=

但我收到了一个错误KeyError: 'user'。这是什么意思?用户不存在?

整个追溯:

Traceback (most recent call last):
  File "<input>", line 259, in <module>
  File "<input>", line 205, in main
  File "/home/vojtam/Desktop/mydb/db.py", line 25, in __init__
    user=config["books"]["user"],
  File "/usr/lib/python3.8/configparser.py", line 960, in __getitem__
    raise KeyError(key)
KeyError: 'user'

【问题讨论】:

  • 包括你得到的整个回溯。
  • 您在配置查询中缺少该部分。试试config['books']['user']

标签: python ini configparser


【解决方案1】:

您需要先从配置中访问books 部分:

from configparser import ConfigParser
import pymysql as mysql

class DatabaseG:
    def __init__(self):
        config = ConfigParser()
        config.read("config.ini")
        books_config = config["books"]
        self.connection = mysql.connect(
                user=books_config["user"],
                passwd=books_config["password"],
                host=books_config["host"],
                db=books_config["database"],
        )
        self.cursor = self.connection.cursor()
        query = """
                CREATE TABLE BOOKS (book_url TEXT, book_id)
                """

        self.cursor.execute(query)

db = DatabaseG()

【讨论】:

  • 感谢您的回答,但没有帮助。请查看我的编辑
  • @vojta 不,此代码不可能出现该错误。再次运行您的代码。
  • 对不起,我忘记更新 Traceback
  • @vojta 你用的是config.ini 看起来一模一样吗?
  • 是的,使用您的解决方案并假设我在我的用户中有错误点击
猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多