简体   繁体   English

从配置文件 Python 中读取值

[英]Read Value from Config File Python

I have a file .env file contain 5 lines我有一个文件.env文件包含 5 行

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我想写python来抓取DB_DATABASE的值我想要这个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.但是有些人可能会更改配置文件的顺序,这就是为什么我不选择 linecache。


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 ?有人可以在这里给我一点推动吗?

Have a look at the config parser: https://docs.python.org/3/library/configparser.html看看配置解析器: https : //docs.python.org/3/library/configparser.html

It's more elegant than a self-made solution它比自制的解决方案更优雅

Modify your .env to将您的 .env 修改为

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

Python code Python代码

#!/usr/local/bin/python
import configparser
config = configparser.ConfigParser()
config.read('test.env')
print config.get('DB','DB_DATABASE')

Output:输出:

bheng-local本地

Read https://docs.python.org/3/library/configparser.html阅读https://docs.python.org/3/library/configparser.html

This should work for you这应该适合你

#!/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]
#!/usr/local/bin/python

from configobj import ConfigObj
conf = ConfigObj('test.env')
print conf['DB_DATABASE']
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)

This could be another option这可能是另一种选择

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

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