简体   繁体   English

Python ConfigParser无法正确搜索.ini文件(Ubuntu 14,Python 3.4)

[英]Python ConfigParser cannot search .ini file correctly (Ubuntu 14, Python 3.4)

Problem: The code compiles fine but when ever i call the read_db_config function i get "Exception: mysql not found in the mysql_config.ini file" 问题:代码编译正常,但是每当我调用read_db_config函数时,都会出现“异常:在mysql_config.ini文件中找不到mysql”

The file is in the same directory but the main script runs two directories up using 该文件位于同一目录中,但主脚本使用以下命令向上运行两个目录

import sys 
from Config.MySQL.python_mysql_dbconfig import read_db_config

I am new to python and have searched everywhere but i cannot seem to pinpoint my issue 我是python的新手,已经到处搜索了,但是我似乎无法指出我的问题

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_config.ini:

[mysql]
database = testdba
user = root
password = test
unix_socket = /opt/lampp/var/mysql/mysql.sock

if you use relative paths for file or directory names python will look for them (or create them) in your current working directory (the $PWD variable in bash). 如果您使用相对路径作为文件或目录名称,则python会在当前工作目录 (bash中的$PWD变量)中查找(或创建)它们。

if you want to have them relative to the current python file, you can use (python 3.4) 如果您想让它们相对于当前的python文件,可以使用(python 3.4)

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

or (python 2.7) 或(python 2.7)

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

if your mysql_config.ini file lives in the etc directory below your python script. 如果您的mysql_config.ini文件位于python脚本下面的etc目录中。

you could of course always use absolute paths (starting with a / ; ie /home/someuser/mysql_config.ini ). 您当然可以始终使用绝对路径(以/开头,即/home/someuser/mysql_config.ini )。

I ran it again but with the modification of adding 我再次运行它,但添加了修改

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

and I found that this created the file "mysql_config.ini" not in the directory where the python "read_db_config" was stored but the parent directory of main python module which calls this module. 并且我发现这不是在存储python“ read_db_config”的目录中而是在调用此模块的主python模块的父目录中创建的文件“ mysql_config.ini”。 I searched it up a bit and figured out a perment solution the lets me keep the "mysql_config.ini" where I wish. 我搜索了一下,找出了一个解决方案,使我可以将“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM