【问题标题】:Section postgresql not found in the database.ini file在 database.ini 文件中找不到部分 postgresql
【发布时间】:2018-03-21 12:11:59
【问题描述】:

我正在尝试在我的数据库 (postgresql 9.6) 中创建表,当我启动我的 python 脚本执行此操作时,它会返回以下类型的错误:

“在 $FILEDIR/database.ini 文件中找不到部分 postgresql”

解析器似乎无法读取该部分,但我不明白为什么。

这是我的配置方法:

def config(filename='$FILEDIR/database.ini', section='postgresql'):

    parser = ConfigParser()
    parser.read(filename)

    db = {}

    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    return db

数据库.ini:

[postgresql]
host=localhost
database=mydatabase
user=myuser
password=mypassword

我已经尝试了this following thread 中的答案,但它对我一点帮助都没有。有人知道原因吗?我正在使用 python 2.7 并且我已经为依赖项执行了“pip install config”和“pip install configparser”。

【问题讨论】:

  • 我不认为 python 知道$FILEDIR 是什么。尝试 .ini 文件的绝对路径。
  • 天啊。就这么简单,我怎么可能没想到。非常感谢!

标签: python python-2.7 configparser


【解决方案1】:

我也遇到了同样的问题,通过将整个文件路径放入 config 中的 kwarg 来解决:

def config(filename='/Users/gramb0t/Desktop/python-postgre/data/database.ini', section='postgresql'):

【讨论】:

    【解决方案2】:
    #just remove the $FILEDIR. it worked for me.
    
    from configparser import ConfigParser
    
    def config(filename="database.ini", section="postgresql"):
        # create a parser
        parser = ConfigParser()
        # read config file
        parser.read(filename)
    
        # get section, default to postgresql
        db = {}
        if parser.has_section(section):
            params = parser.items(section)
            for param in params:
                db[param[0]] = param[1]
        else:
            raise Exception(
                "Section {0} not found in the {1} file".format(section, filename)
            )
    
        return db
    

    【讨论】:

    • 欢迎来到 StackOverflow。请考虑检查格式,从代码中移出文本注释以将其包含在您的答案文本中,并添加更多解释以进行详细说明。
    【解决方案3】:

    路径中的问题 为了解决这个问题,您可以使用 os 来获取 database.ini 的目录,如下例所示

    import os
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    params = config(filename=BASE_DIR+'\memory\database.ini', section='postgresql_pc__server')
    

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2016-10-03
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多