Python ConfigParser cannot correctly search for .ini file (Ubuntu 14, Python 3.4)

Problem: The code compiles fine, but when I call the read_db_config function, I get "Exception: mysql not found in mysql_config.ini file"

The file is in the same directory, but the main script starts two directories with

import sys 
from Config.MySQL.python_mysql_dbconfig import read_db_config

I am new to python and searched everywhere, but I cannot pinpoint my problem.

code:

from ConfigParser import ConfigParser

def read_db_config(filename='mysql_config.ini', section='mysql'):

    # create parser and read ini configuration file
    parser = ConfigParser()
    parser.read(filename)

    # get section, default to mysql
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('{0} not found in the {1}  file'.format(section, filename))

    return db

mysql_config.ini:

[mysql]
database = testdba
user = root
password = test
unix_socket = /opt/lampp/var/mysql/mysql.sock
+1
source share
2 answers

if you use relative paths for file or directory names, python will look for them (or create them) in your current working directory (variable $PWDin bash).

if you want them to refer to the current python file you can use (python 3.4)

from pathlib import Path
HERE = Path(__file__).parent.resolve()
CONFIG_PATH = HERE / '../etc/mysql_config.ini'

(python 2.7)

import os.path
HERE = os.path.abspath(os.path.dirname(__file__))
CONFIG_PATH = os.path.join(HERE, '../etc/mysql_config.ini')

mysql_config.ini etc python script.

, , ( /, .. /home/someuser/mysql_config.ini).

+1

,

parser = configparser.ConfigParser()
parser['mysql'] = {'database': 'testdba',
                   'user' : 'root',
                   'password' : 'test',
                   'unix_socket' : '/opt/lampp/var/mysql/mysql.sock'}
with open('mysql_config.ini', 'w') as configfile:
parser.write(configfile

, "mysql_config.ini" , python "read_db_config", python, . perment, "mysql_config.ini" , .

import configparser 

def read_db_config(dirname = '/opt/Python_MySQL_Email_Receipt_Client/Config/MySQL/', filename='mysql_config.ini', section='mysql'):

# create parser and read ini configuration file

parser = configparser.ConfigParser()
parser.read(dirname + filename)

# get section, default to mysql
db = {}
if parser.has_section(section):
    items = parser.items(section)
    for item in items:
        db[item[0]] = item[1]
else:
    raise Exception('{0} not found in the {1} file'.format(section, filename))

return db
0

Source: https://habr.com/ru/post/1611386/


All Articles