Python ConfigParser - 模块对象在 Fedora 23 中不可调用

Python ConfigParser - module object is not callable in Fedora 23

正在尝试从 python 读取 .ini 数据库文件以测试与 PostGres 数据库的连接

Python 版本 2.7.11

在 Fedora 中,我安装了

sudo dnf 安装python-configparser

安装 1 个包

总下载大小:41k 安装尺寸:144k 这样可以吗[y/N]:是的 下载包:

python-configparser-3.5.0b2-0.2.fc23.noarch.rpm 40 kB/s | 41 KB 00:01

共 31 个 kB/s | 41 KB 00:01 运行 交易检查 交易检查成功。 运行交易测试 事务测试成功。 运行 交易 安装:python-configparser-3.5.0b2-0.2.fc23.noarch 1/1 验证:python-configparser-3.5.0b2-0.2.fc23.noarch 1/1

已安装: python-configparser.noarch 3.5.0b2-0.2.fc23


在我的 config.py 我做了一个

导入配置分析器

当我 运行 我的脚本时,我得到 'module' object is not callable

db.ini

[test1]
host=IP address
database=db
port=5432
user=username
password=pswd

[test2]
host=localhost
database=postgres
port=7999
user=abc
password=abcd

config.py

#!/usr/bin/env python
#from configparser import ConfigParser
import configparser


def config(filename='database.ini', section='gr'):
    # create a parser
    parser = configparser()
    # read config file
    parser.read(filename)

    # get section, default to gr
    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

testing.py

#!/usr/bin/env python
import psycopg2
from config import config



def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)

        # create a cursor
        cur = conn.cursor()

 # execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)

     # close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')


if __name__ == '__main__':
    connect()

[root@svr mytest]# ./testing.py 'module' 对象不可调用

有什么想法吗? 谢谢。

您在创建解析器时出错,请参阅 ConfigParser examples:

An example of reading the configuration file again:

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.cfg')

在Python、a module is basically just a file中,所以如果你想使用这个模块中的任何东西,你必须从你想要的模块中指定what。在您的情况下,将行更改为

# create a parser
parser = configparser.ConfigParser()

这样,您就可以使用模块中的 class ConfigParser

您还可以使用以下方法导入解析器:

from configparser import ConfigParser

而不是

import configparser

我遇到了和你一样的问题,这对我有用。