Read Value from Config File Python

时间:2017-03-02 23:44:38

标签: python configuration environment-variables

I have a file .env file contain 5 lines

DB_HOST=http://localhost/
DB_DATABASE=bheng-local
DB_USERNAME=root
DB_PASSWORD=1234567890
UNIX_SOCKET=/tmp/mysql.sock

I want to write python to grab the value of DB_DATABASE I want this bheng-local


I would have use

import linecache
print linecache.getline('.env', 2)

But some people might change the order of the cofigs, that's why linecache is not my option.


I am not sure how to check for only some strings match but all the entire line, and grab the value after the =.

I'm kind of stuck here :

file = open('.env', "r")
read = file.read()
my_line = ""

for line in read.splitlines():
    if line == "DB_DATABASE=":
        my_line = line
        break
print my_line

Can someone please give me a little push here ?

5 个答案:

答案 0 :(得分:4)

看一下配置解析器: https://docs.python.org/3/library/configparser.html

它比自制解决方案更优雅

答案 1 :(得分:3)

这应该对你有用

#!/usr/local/bin/python
file = open('test.env', "r")
read = file.read()

for line in read.splitlines():
    if 'DB_DATABASE=' in line:
        print line.split('=',1)[1]

答案 2 :(得分:2)

将.env修改为

for x in sent:
    for y in x:
        if y[0] not in dicts.keys():
            dicts[y[0]] = 1
        else:
            dicts[y[0]] += 1

Python代码

[DB]
DB_HOST=http://localhost/
DB_DATABASE=bheng-local
DB_USERNAME=root
DB_PASSWORD=1234567890
UNIX_SOCKET=/tmp/mysql.sock

输出:

  

bheng本地

答案 3 :(得分:1)

#!/usr/local/bin/python

from configobj import ConfigObj
conf = ConfigObj('test.env')
print conf['DB_DATABASE']

答案 4 :(得分:1)

from os import environ, path
from dotenv import load_dotenv

basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))
DB_DATABASE = environ.get('DB_DATABASE')
print(DB_DATABASE)

这可能是另一种选择