2010-08-29 120 views
92

鑑於以下格式(的.properties的.ini):屬性文件在Python(類似於Java屬性)

propertyName1=propertyValue1 
propertyName2=propertyValue2 
... 
propertyNameN=propertyValueN 

對於的Java存在Properties類,它提供的功能解析/與上述格式進行交互。

python's standard library(2.x)?是否有類似的東西?

如果不是,我還有其他的替代方案嗎?

+4

這不是Java的問題。你爲什麼回滾Java標籤刪除? – BalusC 2010-08-29 16:09:10

回答

48

對於.ini文件,有ConfigParser模塊提供與.ini文件兼容的格式。

無論如何,沒有什麼可用於解析完整的.properties文件,當我必須這樣做時,我只是簡單地使用jython(我正在談論腳本)。

+9

如果您不想使用Jython,pyjavaproperties似乎是一個選項:https://bitbucket.org/jnoller/pyjavaproperties – 2011-11-16 19:46:27

+1

java屬性文件不等同於.ini文件。pyjavaproperties是正確的答案 – igni 2014-12-01 19:51:23

+2

Alex Matelli建議使用ConfigParser解析.properties文件的簡單方法http://stackoverflow.com/a/2819788/15274 – 2015-04-16 16:38:59

6

這不完全屬性,但Python確實有一個nice library解析配置文件。另請參閱此配方:A python replacement for java.util.Properties

+0

+1用於查看樹木的森林。 – chb 2012-04-29 13:59:52

+1

第二個鏈接...這不再積極發展。 Jesse Noller從這個配方中創建了一個項目,其中一些修補程序在此處不可用。作者建議項目給任何使用此配方的人。 http://pypi.python.org/pypi/pyjavaproperties – 2014-02-21 20:02:25

2

This是一對一替換java.util.Propeties

從DOC:

def __parse(self, lines): 
     """ Parse a list of lines and create 
     an internal property dictionary """ 

     # Every line in the file must consist of either a comment 
     # or a key-value pair. A key-value pair is a line consisting 
     # of a key which is a combination of non-white space characters 
     # The separator character between key-value pairs is a '=', 
     # ':' or a whitespace character not including the newline. 
     # If the '=' or ':' characters are found, in the line, even 
     # keys containing whitespace chars are allowed. 

     # A line with only a key according to the rules above is also 
     # fine. In such case, the value is considered as the empty string. 
     # In order to include characters '=' or ':' in a key or value, 
     # they have to be properly escaped using the backslash character. 

     # Some examples of valid key-value pairs: 
     # 
     # key  value 
     # key=value 
     # key:value 
     # key  value1,value2,value3 
     # key  value1,value2,value3 \ 
     #   value4, value5 
     # key 
     # This key= this value 
     # key = value1 value2 value3 

     # Any line that starts with a '#' is considerered a comment 
     # and skipped. Also any trailing or preceding whitespaces 
     # are removed from the key/value. 

     # This is a line parser. It parses the 
     # contents like by line. 
52

Java屬性文件是經常有效的Python代碼。您可以將您的myconfig.properties文件重命名爲myconfig.py。然後,只需導入您的文件,這樣

import myconfig 

和訪問屬性直接

print myconfig.propertyName1 
+1

不是一個壞主意..應該是'import myconfig',雖然沒有'.py' – armandino 2011-11-28 19:46:07

+8

我喜歡這個主意,但它不適用於包含點的屬性,即'prop.name =「val」'在這種情況下不起作用。 – maxjakob 2012-04-23 14:38:38

+27

'Java屬性文件是有效的Python代碼':我必須有所不同。 *一些* Java屬性文件將通過有效的Python代碼,但當然不是全部。正如@mmjj所說,點是一個問題。所以沒有引號的文字字符串。 -1。 – 2012-05-02 12:45:29

13

如果你有我建議使用的.ini和Python的ConfigParser如上述文件格式的選項。如果您需要與Java .properties文件兼容,我已經爲它編寫了一個名爲jprops的庫。我們使用pyjavaproperties,但遇到各種限制後,我最終實現了自己的。它完全支持.properties格式,包括unicode支持和更好的轉義序列支持。 Jprops還可以解析任何類似文件的對象,而pyjavaproperties只能用於磁盤上的真實文件。

+1

我只是試了一下。奇蹟般有效。 MattGood +1! – 2012-05-11 20:05:18

2

這是我在我的項目正在做的:我剛剛創建另一個.py文件名爲properties.py其中包括我使用的所有公共變量/屬性在該項目,並在任何文件需要使用這些變量,把

from properties import *(or anything you need) 

用這種方法來保持SVN和平,當我改變dev的位置頻繁且相當相對於當地環境的一些常用變量是。對我來說工作正常,但不確定這種方法會被建議用於正式的開發環境等。

37

我能夠得到這個與ConfigParser一起工作,沒有人展示如何做到這一點的任何示例,所以這裏是一個簡單的python讀者的屬性文件和屬性文件的例子。請注意,擴展名仍然是.properties,但我必須添加一個類似於.ini文件中看到的節標題...有點混雜,但它的工作原理。

蟒蛇文件:PythonPropertyReader.py

#!/usr/bin/python  
import ConfigParser 
config = ConfigParser.RawConfigParser() 
config.read('ConfigFile.properties') 

print config.get('DatabaseSection', 'database.dbname'); 

屬性文件:ConfigFile.properties

[DatabaseSection] 
database.dbname=unitTest 
database.user=root 
database.password= 

實現更多的功能,請閱讀:https://docs.python.org/2/library/configparser.html

0

我這樣做是使用ConfigParser如下。該代碼假定存在在同一目錄中的文件config.prop地方叫BaseTest放置:

config.prop

[CredentialSection] 
app.name=MyAppName 

BaseTest.py:

import unittest 
import ConfigParser 

class BaseTest(unittest.TestCase): 
    def setUp(self): 
     __SECTION = 'CredentialSection' 
     config = ConfigParser.ConfigParser() 
     config.readfp(open('config.prop')) 
     self.__app_name = config.get(__SECTION, 'app.name') 

    def test1(self): 
     print self.__app_name % This should print: MyAppName 
31

我知道,這是一個非常古老的問題,但我現在需要它,我決定實施我自己的解決方案,一個純粹的Python解決方案,涵蓋大多數用例(並非全部):

def load_properties(filepath, sep='=', comment_char='#'): 
    """ 
    Read the file passed as parameter as a properties file. 
    """ 
    props = {} 
    with open(filepath, "rt") as f: 
     for line in f: 
      l = line.strip() 
      if l and not l.startswith(comment_char): 
       key_value = l.split(sep) 
       key = key_value[0].strip() 
       value = sep.join(key_value[1:]).strip().strip('"') 
       props[key] = value 
    return props 

您可以更改sep以 ':' 來解析的文件格式有:

key : value 

代碼解析正確線,如:

url = "http://my-host.com" 
name = Paul = Pablo 
# This comment line will be ignored 

你會得到一個字典有:

{"url": "http://my-host.com", "name": "Paul = Pablo" } 
+0

頂尖的解決方案,正是我一直在尋找的! – Russell 2016-08-23 14:58:55

+0

請注意,這不支持與像'foo =「bar」#bat'這樣的條目在同一行上的註釋。 – ThomasW 2017-08-09 04:50:25

2

我創建了一個python模塊,它幾乎類似於Java的Properties類(實際上它就像在PropertyPlaceholderConfigurer中的spr它可以讓你使用$ {variable-reference}引用已定義的屬性)

編輯:你可以通過運行命令(目前測試的python 3)來安裝這個軟件包。
pip install property

該項目上GitHub

例託管:(詳細資料可以發現here

比方說,你在my_file.properties定義了以下屬性文件

foo = I am awesome 
bar = ${chocolate}-bar 
chocolate = fudge 

加載上述屬性的代碼

from properties.p import Property 

prop = Property() 
# Simply load it into a dictionary 
dic_prop = prop.load_property_files('my_file.properties') 
+0

舉一些例子..如何使用它... – Moumit 2016-05-28 18:45:27

+0

比方說,你在my_file.properties定義了以下屬性文件 富=我真棒 欄= $ {巧克力} -bar 巧克力軟糖= 代碼加載上述屬性 prop = Property() prop.load('path/to/my_file.properties') prop.get('foo')#我很棒 prop.get('bar')#軟糖條 – 2016-05-28 19:04:07

+0

請編輯你的答案並在那裏解釋.. – Moumit 2016-05-28 19:07:10

1
import json 
f=open('test.json') 
x=json.load(f) 
f.close() 
print(x) 

test.json的內容: { 「主人」:「127.0.0。1" ,‘用戶’:‘JMS’}

0

這是我寫的解析文件,並將其設置爲其中跳過的意見,並添加切換到指定 汞柱非鍵值線ENV變量:d

  • -h或--help打印使用摘要
  • -c指定炭,在丙文件
  • 標識評論

  • -s分離鍵和值之間,並指定需要被解析例如屬性文件:蟒 EnvPar amSet.py〜C#-s = env.properties

    import pipes 
    import sys , getopt 
    import os.path 
    
    class Parsing : 
    
         def __init__(self , seprator , commentChar , propFile): 
         self.seprator = seprator 
         self.commentChar = commentChar 
         self.propFile = propFile 
    
        def parseProp(self): 
         prop = open(self.propFile,'rU') 
         for line in prop : 
          if line.startswith(self.commentChar)==False and line.find(self.seprator) != -1 : 
           keyValue = line.split(self.seprator) 
           key = keyValue[0].strip() 
           value = keyValue[1].strip() 
             print("export %s=%s" % (str (key),pipes.quote(str(value)))) 
    
    
    
    
    class EnvParamSet: 
    
        def main (argv): 
    
         seprator = '=' 
         comment = '#' 
    
         if len(argv) is 0: 
          print "Please Specify properties file to be parsed " 
          sys.exit() 
         propFile=argv[-1] 
    
    
         try : 
          opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="]) 
         except getopt.GetoptError,e: 
          print str(e) 
          print " possible arguments -s <key value sperator > -c < comment char > <file> \n Try -h or --help " 
          sys.exit(2) 
    
    
         if os.path.isfile(args[0])==False: 
          print "File doesnt exist " 
          sys.exit() 
    
    
         for opt , arg in opts : 
          if opt in ("-h" , "--help"): 
           print " hg:d \n -h or --help print usage summary \n -c Specify char that idetifes comment \n -s Sperator between key and value in prop file \n specify file " 
           sys.exit() 
          elif opt in ("-s" , "--seprator"): 
           seprator = arg 
          elif opt in ("-c" , "--comment"): 
           comment = arg 
    
         p = Parsing(seprator, comment , propFile) 
         p.parseProp() 
    
        if __name__ == "__main__": 
          main(sys.argv[1:]) 
    
1

這是一個非常古老的問題..但仍...

如果您需要在性能部分讀出所有值文件以簡單的方式:

你config.properties文件佈局:

[SECTION_NAME]

鍵1 =值

鍵2 =值

您代碼:

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'} 
1

您可以使用ConfigParser.RawConfigParser.readfp這裏定義一個類文件對象 - >https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp

定義,它覆蓋readline認爲的實際內容前添加一個節名稱類的屬性文件。

我已將它打包到返回所定義的所有屬性的dict的類中。

import ConfigParser 

class PropertiesReader(object): 

    def __init__(self, properties_file_name): 
     self.name = properties_file_name 
     self.main_section = 'main' 

     # Add dummy section on top 
     self.lines = [ '[%s]\n' % self.main_section ] 

     with open(properties_file_name) as f: 
      self.lines.extend(f.readlines()) 

     # This makes sure that iterator in readfp stops 
     self.lines.append('') 

    def readline(self): 
     return self.lines.pop(0) 

    def read_properties(self): 
     config = ConfigParser.RawConfigParser() 

     # Without next line the property names will be lowercased 
     config.optionxform = str 

     config.readfp(self) 
     return dict(config.items(self.main_section)) 

if __name__ == '__main__': 
    print PropertiesReader('/path/to/file.properties').read_properties() 
0

下面兩行代碼顯示瞭如何使用Python List Comprehension加載'java style'屬性文件。

split_properties=[line.split("=") for line in open('/<path_to_property_file>)] 
properties={key: value for key,value in split_properties } 

請各位看看下面職位的詳細信息 https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/

+0

代碼不關閉文件對象,也只是鏈接回答不受歡迎。 – aristotll 2017-12-05 10:43:23

+0

該解決方案不包括多行值或包含等號的值。 – 2017-12-21 20:53:12