Python ConfigParser 无法正确搜索 .ini 文件(Ubuntu 14、Python 3.4) [英] Python ConfigParser cannot search .ini file correctly (Ubuntu 14, Python 3.4)
问题描述
问题:代码编译得很好,但是当我调用 read_db_config 函数时,我得到异常:在 mysql_config.ini 文件中找不到 mysql"
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"
文件在同一目录中,但主脚本使用
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
我是 python 新手,到处搜索,但我似乎无法查明我的问题
I am new to python and have searched everywhere but i cannot seem to pinpoint my issue
代码:
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
推荐答案
如果您使用 相对路径 作为文件或目录名称,python 将在您的 当前工作目录(bash中的$PWD
变量).
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 文件,你可以使用 (python 3.4)
if you want to have them relative 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)
or (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
文件位于 Python 脚本下的 etc
目录中.
if your mysql_config.ini
file lives in the etc
directory below your python script.
您当然可以始终使用绝对路径(以 /
开头;即 /home/someuser/mysql_config.ini
).
you could of course always use absolute paths (starting with a /
; i.e. /home/someuser/mysql_config.ini
).
这篇关于Python ConfigParser 无法正确搜索 .ini 文件(Ubuntu 14、Python 3.4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!