如何在PYTHON中读取属性文件

8dtrkrch  于 2022-09-18  发布在  Java
关注(0)|答案(7)|浏览(226)

我有一个名为Configuration.properties的属性文件,其中包含:

path=/usr/bin
db=mysql
data_path=/temp

我需要读取该文件,并在后续脚本中使用pathdbdata_path等变量。我可以使用configParser来完成此操作,还是只需读取文件并获取值即可。

提前谢谢你。

ffdz8vbo

ffdz8vbo1#

对于没有节头、被[]包围的配置文件,您会发现抛出了ConfigParser.NoSectionError异常。可以通过插入“假”部分标题来解决这个问题--如下面的答案所示。

如果文件很简单,如pcalcao's answer所述,您可以执行一些字符串操作来提取值。

下面是一段代码片段,它返回配置文件中每个元素的键-值对词典。

separator = "="
keys = {}

# I named your file conf and stored it

# in the same directory as the script

with open('conf') as f:

    for line in f:
        if separator in line:

            # Find the name and value by splitting the string
            name, value = line.split(separator, 1)

            # Assign key value pair to dict
            # strip() removes white space from the ends of strings
            keys[name.strip()] = value.strip()

print(keys)
yrdbyhpb

yrdbyhpb2#

如果您需要以一种简单的方式从属性文件的某一节中读取所有值:

您的config.properties文件布局:

[SECTION_NAME]  
key1 = value1  
key2 = value2

您可以编写代码:

import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.properties file')

   details_dict = dict(config.items('SECTION_NAME'))

这将为您提供一个字典,其中的键与配置文件中的键及其相应值相同。

details_dict为:

{'key1':'value1', 'key2':'value2'}

现在获取key1的值:details_dict['key1']

将其全部放入一个方法中,该方法只从配置文件中读取该节一次(在程序运行期间第一次调用该方法时)。

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict

现在调用上面的函数并获取所需键的值:

config_details = get_config_dict()
key_1_value = config_details['key1']

-----------

扩展了上面提到的方法,自动逐节读取,然后按节名和键名访问。

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = dict()

        for section in config.sections():
            get_config_section.section_dict[section] = 
                             dict(config.items(section))

    return get_config_section.section_dict

访问:

config_dict = get_config_section()

port = config_dict['DB']['port']

(这里的‘DB’是配置文件中的节名,‘port’是节‘DB’下的键。)

tvz2xvvm

tvz2xvvm3#

我喜欢现在的答案。而且..。我觉得在“真实世界”里有一种更干净的方式。如果您正在进行任何大小或比例的项目,尤其是在多个环境中,则必须使用横断面标题功能。我想把它和格式良好的可复制代码放在这里,使用一个健壮的真实世界示例。这是在Ubuntu 14上运行的,但可以跨平台运行:

真实世界简单示例

An 'Environment-based' configuration

设置示例(端子):
Cd~/my/凉爽/项目触摸本地。属性触摸环境.属性ls-la~/my/Cool/project-rwx-1 www-data www-data 0 Jan 24 23:37 local.properties-rwx-1 www-data www-data 0 Jan 24 23:37 Environmental.properties

设置好的权限

>> chmod 644 local.properties
>> chmod 644 env.properties
>> ls -la
-rwxr--r-- 1 www-data www-data  0 Jan 24 23:37 local.properties
-rwxr--r-- 1 www-data www-data  0 Jan 24 23:37 environ.properties

编辑您的属性文件。

文件1:local.properties

This is YOUR properties file, local to your machine and workspace, and contains sensitive data, don't push to version control!!!

[global]
relPath=local/path/to/images              
filefilters=(.jpg)|(.png)

[dev.mysql]
dbPwd=localpwd
dbUser=localrootuser

[prod.mysql]
dbPwd=5tR0ngpwD!@#
dbUser=serverRootUser

[branch]

# change this to point the script at a specific environment

env=dev

文件2:环境属性

This properties file is shared by everybody, changes are pushed to version control


# ----------------------------------------------------

# Dev Environment

# ----------------------------------------------------

[dev.mysql]
dbUrl=localhost
dbName=db

[dev.ftp]
site=localhost
uploaddir=http://localhost/www/public/images

[dev.cdn]
url=http://localhost/cdn/www/images

# ----------------------------------------------------

# Prod Environment

# ----------------------------------------------------

[prod.mysql]
dbUrl=http://yoursite.com:80
dbName=db

[prod.ftp]
site=ftp.yoursite.com:22
uploaddir=/www/public/

[prod.cdn]
url=http://s3.amazon.com/your/images/

Python文件:readCfg.py

This script is a re-usable snippet to load a list of configuration files导入ConfigParser导入操作系统


# a simple function to read an array of configuration files into a config object

def read_config(cfg_files):
    if(cfg_files != None):
        config = ConfigParser.RawConfigParser()

        # merges all files into a single config
        for i, cfg_file in enumerate(cfg_files):
            if(os.path.exists(cfg_file)):
                config.read(cfg_file)

        return config

Python文件:您的CoolProgram.py

This program will import the file above, and call the 'read_config' method

from readCfg import read_config

# merge all into one config dictionary

config      = read_config(['local.properties', 'environ.properties'])

if(config == None):
    return

# get the current branch (from local.properties)

env      = config.get('branch','env')        

# proceed to point everything at the 'branched' resources

dbUrl       = config.get(env+'.mysql','dbUrl')
dbUser      = config.get(env+'.mysql','dbUser')
dbPwd       = config.get(env+'.mysql','dbPwd')
dbName      = config.get(env+'.mysql','dbName')

# global values

relPath = config.get('global','relPath')
filefilterList = config.get('global','filefilters').split('|')

print "files are: ", fileFilterList, "relative dir is: ", relPath
print "branch is: ", env, " sensitive data: ", dbUser, dbPwd

结论

根据上述配置,您现在可以拥有一个脚本,通过更改‘local.properties’中的[BRANCH]env值来完全更改环境。而这一切都是基于良好的配置原则!啊耶!

kh212irz

kh212irz4#

一个用于在忽略注解的情况下读取非结构化属性文件(无节)的内联代码:

with open(props_file_path, "r", encoding="utf-8") as f:
    props = {e[0]: e[1] for e in [line.split('#')[0].strip().split('=') for line in f] if len(e) == 2}
qvtsj1bj

qvtsj1bj5#

是的,是的,你可以。

ConfigParser(https://docs.python.org/2/library/configparser.html)将为您提供一个很好的小结构来获取开箱即用的值,手动操作将需要一些字符串拆分,但对于简单的格式化文件,这不是什么大不了的事情。

问题是“我如何阅读此文件?”。

3htmauhk

3htmauhk6#

保持简单。创建一个名称=值对的属性文件,并将其另存为filename.py。然后,您所要做的就是将其导入并将属性引用为name.Value。这就是如何..。

我的Oracle连接配置文件名为config.py,如下所示。

username = "username"
password = "password"
dsn = "localhost/xepdb1"
port = 1521
encoding = "UTF-8"

所以,在巨蟒游戏中,我要做的就是...

import cx_Oracle
import config

conn = None
cursor = None

try:

    print("connecting...");

    conn = cx_Oracle.connect(config.username, config.password, config.dsn, encoding=config.encoding)

    cursor = conn.cursor()

    print("executing...");

    # don't put a ';' at the end of SQL statements!
    cursor.execute("SELECT * FROM employees")

    print("dumping...");

    for row in cursor:
        print(row[0])

except cx_Oracle.Error as error:
    print(error)
finally:
    print("finally...")
    if cursor:
        cursor.close()
    if conn:
        conn.close()
juud5qan

juud5qan7#

If you want to read a proeprties file in python, my first suggestion, which I am myself not following because I like Visual Code too much ...

Is run your python on Jython. And once you run python on Jython, you can trivially open a java util input stream to your data file. And using the java.utl.Properties you can call the load() api, and you are set to go. So my recommendation is, do what is easiest, just start using the java runtime environment and jython along with it.

By the way, I am of course using jython to run python. No questions on that.

But what I am not doing is using jython to debug python... sadly! The problem for me is that I use microsft visual code for writing pythong, and then yeah ... then I am stuck to the my normal python installation. Not an ideal world!

If this would be your situation. Then you can go to plan (b) ... Try to not use JDK libraries and find an alternative else where.

So here is sugestion. This is a library that I found out and and that I am using for the effect of reading properties files. https://pypi.python.org/pypi/jproperties/1.0.1#downloads

from jproperties import Properties
with open("foobar.properties", "r+b") as f:
    p = Properties()
    p.load(f, "utf-8")

    # Do stuff with the p object...

    f.truncate(0)
    p.store(f, encoding="utf-8")

So in the above code quote, you seen how they open properties file. Wipe it out, and write back again the properties into the file.

You tread the properties object as dictionary object. And then you do stuff like:

myPropertiesTuple = propertiesObjec[myPropertyKey]

Be careful. When you use the above api and get a value for a key, that value is a PropertiesTuple. It is a pair of (value,metadata). So the value you would be hunting for you get it from myPropertiesTuple[0]. Other then that, just read the documentation on the page the library works well.

I am using approach (b). If the advantage of using the java libraries at some point outweighs the advantage of being stuck to native python language simply so that I may debug on visual code.

I will I hear beat drop support for pure python runtime and comrpomise the code with hard dependencies jython runtime / java libararies. So far there is no need for it.

So, blue bill or the red pill?

相关问题