簡體   English   中英

如何讀取 python 中的屬性文件

[英]How to read properties file in python

我有一個名為Configuration.properties的屬性文件,其中包含:

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

我需要閱讀此文件並在后續腳本中使用pathdbdata_path等變量。 我可以使用 configParser 還是簡單地讀取文件並獲取值來執行此操作。

提前致謝。

對於沒有節頭的配置文件,用[]包圍 - 你會發現拋出ConfigParser.NoSectionError異常。 通過插入“假”部分標題可以解決此問題- 如本答案所示

如果文件很簡單,如pcalcao 的回答中所述,您可以執行一些字符串操作來提取值。

這是一個代碼片段,它返回配置文件中每個元素的鍵值對字典。

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)

如果您需要以簡單的方式從屬性文件中的某個部分讀取所有值:

您的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'部分下的一個鍵。)

我喜歡當前的答案。 而且......我覺得在“真實世界”中有一種更清潔的方法。 如果您正在執行任何規模或規模的項目,尤其是在“多”環境領域,則必須使用節標題功能。 我想把它和格式良好的可復制代碼放在一起,使用一個健壯的現實世界的例子。 這在 Ubuntu 14 中運行,但跨平台工作:

真實世界的簡單示例


設置示例(終端):

cd ~/my/cool/project touch local.properties touch environ.properties 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:37environ.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

[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:environ.properties

#----------------------------------------------------
# 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

import ConfigParser import osimport ConfigParser import os

# 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 文件:yourCoolProgram.py

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 值來完全改變環境的腳本。 而這一切都是基於良好的配置原則! 耶!

是的,是的,你可以。

ConfigParser ( https://docs.python.org/2/library/configparser.html ) 將為您提供一個很好的小結構來從開箱即用中獲取值,手動操作將需要一些字符串拆分,但對於一個簡單的格式文件,沒什么大不了的。

問題是“我如何閱讀這個文件?”。

一個用於讀取非結構化屬性文件(無節)而忽略注釋的襯墊:

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}

保持簡單。 創建名稱=值對的屬性文件並將其保存為 filename.py。 然后您所要做的就是導入它並將屬性引用為 name.value。 就是這樣...

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

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

所以,在 Python 中,我所要做的就是......

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()

如果你想在 python 中讀取一個 proeprties 文件,我的第一個建議,我自己沒有遵循,因為我太喜歡 Visual Code ......

在 Jython 上運行你的 python。 一旦您在 Jython 上運行 python,您就可以輕松地打開一個 java util 輸入流到您的數據文件。 使用 java.utl.Properties 可以調用 load() api,然后就可以開始了。 所以我的建議是,做最簡單的事情,開始使用 java 運行時環境和 jython。

順便說一句,我當然是使用 jython 來運行 python 的。 對此沒有任何疑問。

但是我沒有做的是使用 jython 來調試 python ......可悲的是! 對我來說問題是我使用 microsft 可視化代碼來編寫 pythong,然后是的......然后我被困在我的正常 python 安裝中。 不是理想的世界!

如果這就是你的情況。 然后你可以去計划(b)......盡量不使用JDK庫並在其他地方找到替代方案。

所以這里是sugestion。 這是我發現的一個庫,我正在使用它來讀取屬性文件。 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")

所以在上面的代碼引用中,你看到了他們如何打開屬性文件。 擦除它,然后再次將屬性寫回到文件中。

您將屬性對象視為字典對象。 然后你做這樣的事情:

myPropertiesTuple = propertiesObjec[myPropertyKey]

當心。 當您使用上述 api 並獲取鍵的值時,該值是一個 PropertiesTuple。 它是一對(值,元數據)。 因此,您要尋找的值可以從 myPropertiesTuple[0] 中獲取。 除此之外,只需閱讀該庫運行良好的頁面上的文檔。

我正在使用方法(b)。 如果在某些時候使用 java 庫的優勢超過了堅持使用原生 python 語言的優勢,以便我可以調試可視化代碼。

我將聽到對純 python 運行時的節拍支持,並使用硬依賴項 jython 運行時/java 庫對代碼進行妥協。 到目前為止還沒有必要。

那么,藍色賬單還是紅色葯丸?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM