相关文章推荐
冷冷的鸭蛋  ·  GetChildren Method ...·  1 年前    · 
豪气的消防车  ·  java - ...·  1 年前    · 

python中的属性文件(类似于Java属性)。

153 人关注

鉴于以下格式( .properties or .ini ):

propertyName1=propertyValue1
propertyName2=propertyValue2
propertyNameN=propertyValueN

For 爪哇 there is the Properties类,提供解析/交互上述格式的功能。

是否有类似的东西在python's 标准库(2.x) ?

如果没有,我还有什么其他选择?

2 个评论
这不是一个Java问题。你为什么要回滚Java标签的删除?
你可以查看我的帖子,关于Python中的Spring配置替代方案。 code.massoudafrashteh.com/manage-dev-prod-config in-python
python
properties
configparser
Andrei Ciobanu
Andrei Ciobanu
发布于 2010-08-29
25 个回答
James Oravec
James Oravec
发布于 2019-02-24
已采纳
0 人赞同

我能够让这个东西在 ConfigParser 下工作,没有人显示任何关于如何做的例子,所以这里有一个简单的属性文件的python阅读器和属性文件的例子。请注意,扩展名仍然是 .properties ,但我不得不添加一个类似于你在.ini文件中看到的部分标题......有点私生子的感觉,但它是有效的。

The python file: PythonPropertyReader.py

#!/usr/bin/python    
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')
print config.get('DatabaseSection', 'database.dbname');

The property file: ConfigFile.properties

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

有关更多的功能,请阅读。https://docs.python.org/2/library/configparser.html

在 Python 3 中,ConfigParser 模块已被改名为 configparser。
这是针对.ini文件,而不是.properties文件,因为它们不包含章节,而且如果configParser没有找到任何章节头,它就会失败。此外,ini文件可能不包括章节,所以这个configParser看起来一点也不可靠。
pygabriel
pygabriel
发布于 2019-02-24
0 人赞同

For .ini files there is the configparser 模块,提供与 .ini 文件兼容的格式。

总之,没有任何东西可以用来解析完整的 .properties 文件,当我必须这样做的时候,我只是用jython(我说的是脚本)。

如果你不想使用Jython,pyjavaproperties似乎是一个选择。 bitbucket.org/jnoller/pyjavaproperties
igni
java属性文件不等同于.ini文件。 pyjavaproperties是正确答案。
pi.
Alex Matelli提出了一个用ConfigParser解析.properties文件的简单方法。 stackoverflow.com/a/2819788/15274
bitbucket.org/jnoller/pyjavaproperties自2010年以来没有被维护。它与python 3不兼容。我将使用@pi所链接的解决方案。
mpe
由于这里没有任何地方提到它,让我再次补充,这是不一样的。我不能为Java或Py3说话,也许它对简单的键/值有效。但是字符串插值的语法是不同的。 这个解决方案提供了Python格式化,即%(string)s,而(例如Ant)我会使用${string}。 pymotw.com/2/ConfigParser
Roberto
Roberto
发布于 2019-02-24
0 人赞同

我知道这是一个非常老的问题,但我现在需要它,我决定实现我自己的解决方案,一个纯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" }
    
一流的解决方案,正是我所寻找的!"。
请注意,这并不支持在同一行中的注释,如 foo = "bar" # bat
bonh
@ThomasW 如果我们使用Java作为事实上的标准,Properties#load会将其视为一个属性 foo ,其值为 "bar" # bat
你认为把一个老问题的答案贴出来有什么意义?重点是我能够通过复制粘贴这个来节省时间,在我的一个azure管道中,而不是自己实现它,所以谢谢:)
我喜欢这个答案! 我为处理内联评论所做的唯一改变是将 l = line.strip() 改为 l = line.split(comment_char)[0].strip() ,然后只检查 l 是否有值,而不是在随后的行中检查 if l:
Travis Bear
Travis Bear
发布于 2019-02-24
0 人赞同

一个java属性文件通常也是有效的python代码。 你可以把你的myconfig.properties文件重命名为myconfig.py。然后只需导入你的文件,像这样

import myconfig

并直接访问这些属性

print myconfig.propertyName1
    
我喜欢这个想法,但它对包含点的属性不起作用,也就是说, prop.name="val" 在这种情况下是不起作用的。
A java properties file is valid python code 。我有不同意见。 Some Java属性文件可以通过有效的python代码,但肯定不是全部。正如@mmjj所说,点是一个问题。无引号的字面字符串也是如此。-1.
一个相当糟糕的想法......因为它已经坏了。 Java道具文件允许用": "代替"=";它们在行延续后吃掉空格;它们不引用字符串。 这些都不是 "有效的 Python"。
一般来说,Java属性文件不会通过有效的python代码。 一种替代方法是在一个python文件中设置你的属性,并使用有效的python(例如:MEDIA_ROOT='/foo') ...
r_2
这是一个最好避免的黑客。 当你的属性发生变化,文件不再是有效的python时,你将会有一个糟糕的一天。
mvallebr
mvallebr
发布于 2019-02-24
0 人赞同

如果你没有多行属性和一个非常简单的需求,几行代码就可以为你解决。

File t.properties :

Python code:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}
    
谢谢,我喜欢直截了当的方式 !
Matt Good
Matt Good
发布于 2019-02-24
0 人赞同

如果你有一个文件格式的选择,我建议使用.ini和Python的ConfigParser,如前所述。 如果你需要与Java .properties文件兼容,我已经为它写了一个库,叫做 jprops . 我们曾使用pyjavaproperties,但在遇到各种限制后,我最终实现了我自己的。 它完全支持.properties格式,包括unicode支持和对转义序列的更好支持。 Jprops还可以解析任何类似文件的对象,而pyjavaproperties只对磁盘上的真实文件工作。

我刚刚试了一下这个。 效果很好。MattGood+1!
如果你加上 pip install 和一个代码例子,你的答案会更好 pip install jprops, with open(path) as fp: properties = jprops.load_properties(fp) print(properties)
Manoj Govindan
Manoj Govindan
发布于 2019-02-24
0 人赞同

这不完全是属性,但Python确实有一个 漂亮的图书馆 用于解析配置文件。也请看这个配方。 java.util.Properties的python替代品 .

对于第二个链接......这已经不再是积极的开发。Jesse noller已经从这个配方中创建了一个项目,其中有一些这里没有的修正。作者向使用这个配方的人推荐这个项目。 pypi.python.org/pypi/pyjavaproperties
Andy Quiroz
Andy Quiroz
发布于 2019-02-24
0 人赞同

我用过这个,这个库非常有用

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'
    
marekjm
marekjm
发布于 2019-02-24
0 人赞同

Here is link to my project: https://sourceforge.net/projects/pyproperties/ .它是一个库,含有处理Python 3.x的*.properties文件的方法。

但它不是基于java.util.Properties的。

tmow
tmow
发布于 2019-02-24
0 人赞同

This 是java.util.Propeties的一对一替换。

From the 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.
    
Alexander Pogrebnyak
Alexander Pogrebnyak
发布于 2019-02-24
0 人赞同

You can use a file-like object in ConfigParser.RawConfigParser.readfp defined here -> 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()
    
MANU
MANU
发布于 2019-02-24
0 人赞同

如果你需要以简单的方式从属性文件的某个部分读取所有值。

Your config.properties file layout :

[SECTION_NAME]  
key1 = value1  
key2 = value2  

You code:

   import configparser
   config = configparser.RawConfigParser()
   config.read('path_to_config.properties file')
   details_dict = dict(config.items('SECTION_NAME'))

这将给你一个字典,其中的键与配置文件中的相同,并有相应的值。

details_dict is :

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

现在来获取key1的值。 【替换代码5

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

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'部分下的一个键)。

Vineet Singh
Vineet Singh
发布于 2019-02-24
0 人赞同

在你的Python模块中创建一个字典,把所有的东西都储存在里面,然后访问它,比如说。

dict = {
       'portalPath' : 'www.xyx.com',
       'elementID': 'submit'}

现在要访问它,你可以简单地做。

submitButton = driver.find_element_by_id(dict['elementID'])
    
强烈建议你分享一些代码样本。目前,你的答案是非常糟糕的
@NikolayShevchenko 对不起,格式不好,我已经更新了我的答案。
Wolfgang Fahl
Wolfgang Fahl
发布于 2019-02-24
0 人赞同

我的Java ini文件没有章节标题,我想要一个dict作为结果。所以我简单地注入了一个"[ini]"部分,让默认的配置库做它的工作。

以eclipse IDE .metadata目录的version.ini fie为例。

#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800
# 'injected' ini section
[ini]
#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800

结果被转换为一个dict。

from configparser import ConfigParser
@staticmethod
    def readPropertyFile(path):
        # https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
        config = ConfigParser()
        s_config= open(path, 'r').read()
        s_config="[ini]\n%s" % s_config
        # https://stackoverflow.com/a/36841741/1497139
        config.read_string(s_config)
        items=config.items('ini')
        itemDict={}
        for key,value in items:
            itemDict[key]=value
        return itemDict
    
注入了一个[ini]? 那是什么意思? 请出示你的配置文件。
@johnktejik - 请看按要求添加的一个例子
festony
festony
发布于 2019-02-24
0 人赞同

这就是我在我的项目中所做的。我只是创建了另一个名为properties.py的文件,其中包括我在项目中使用的所有常用变量/属性,并在任何需要引用这些变量的文件中,把

from properties import *(or anything you need)

当我频繁地更换开发地点时,使用这种方法来保持svn的平静,一些常用的变量与本地环境有很大关系。对我来说很好,但不确定这种方法是否建议用于正式的开发环境等。

user1261273
发布于 2019-02-24
0 人赞同
import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)

Contents of test.json: {"host": "127.0.0.1", "user": "jms"}

Anand Joshi
Anand Joshi
发布于 2019-02-24
0 人赞同

我创建了一个Python模块,它几乎与Java的Properties类相似(实际上它就像spring中的PropertyPlaceholderConfigurer,让你用${variable-reference}来引用已经定义的属性)。

编辑:你可以通过运行命令来安装这个包(目前为python 3测试)。
pip install property

The project is hosted on 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')
    
假设你在my_file.properties文件中定义了以下属性 foo = I am awesome bar = ${chocolate}-bar chocolate = fudge 载入上述属性的代码 prop = Property() prop.load(path/to/my_file.properties') prop.get('foo') # I am awesome prop.get('bar') # fudge-bar
Anand Joshi
Done . Hope it helps
Anoop Isaac
Anoop Isaac
发布于 2019-02-24
0 人赞同

下面2行代码显示了如何使用Python List Comprehension来加载 "java风格 "属性文件。

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/

这段代码没有关闭文件对象,只有链接的答案也不受欢迎。
该解决方案不包括多行值或包括等号的值。
Agrim Bansal
Agrim Bansal
发布于 2019-02-24
0 人赞同

你可以使用参数 "fromfile_prefix_chars "和argparse来读取配置文件,如下所示

temp.py

parser = argparse.ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument('--a')
parser.add_argument('--b')
args = parser.parse_args()
print(args.a)
print(args.b)

config file

hello hello dear
python temp.py "#config"
    
narko
narko
发布于 2019-02-24
0 人赞同

我使用ConfigParser做到了这一点,如下所示。该代码假设在放置BaseTest的同一目录下有一个名为config.prop的文件。

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
    
0 人赞同

这是我写的,用来解析文件,并将其设置为环境变量,跳过注释和非键值行,添加开关来指定

  • -h or --help print usage summary
  • -c Specify char that identifies comment
  • -s Separator between key and value in prop file
  • 并指定需要解析的属性文件,例如: python EnvParamSet.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))))
            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:])
        
  • DGrady
    DGrady
    发布于 2019-02-24
    0 人赞同

    Lightbend公司已经发布了 类型安全配置 库,它可以解析属性文件,也可以解析一些基于JSON的扩展。Lightbend的库只适用于JVM,但它似乎被广泛采用,现在有许多语言的端口,包括Python。 https://github.com/chimpler/pyhocon

    0 人赞同

    你可以使用以下函数,它是@mvallebr的修改后的代码。 它尊重属性文件的注释,忽略空的新行,并允许检索单个键值。

    def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
        Reads a .properties file and returns the key value pairs as dictionary.
        if key value is specified, then it will return its value alone.
        with open(propertiesFile) as f:
            l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
            d = {key.strip(): value.strip() for key, value in l}
            if key:
                return d[key]
            else:
                return d
        
    Andy Quiroz
    Andy Quiroz
    发布于 2019-02-24
    0 人赞同

    this works for me.

    from pyjavaproperties import Properties
    p = Properties()
    p.load(open('test.properties'))
    p.list()
    print p
    print p.items()
    print p['name3']
        
    请删除这个重复的帖子。 顺便说一下,我确实给你的另一个帖子投了赞成票;)
    Vaibhav Shukla
    Vaibhav Shukla
    发布于 2019-02-24
    0 人赞同

    我遵循configparser的方法,对我来说效果很好。创建了一个PropertyReader文件,并在那里使用config parser来准备对应于每个部分的属性。

    **Used Python 2.7

    PropertyReader.py文件的内容。

    #!/usr/bin/python
    import ConfigParser
    class PropertyReader:
    def readProperty(self, strSection, strKey):
        config = ConfigParser.RawConfigParser()
        config.read('ConfigFile.properties')
        strValue = config.get(strSection,strKey);
        print "Value captured for "+strKey+" :"+strValue
        return strValue
    

    读取模式文件的内容。

    from PropertyReader import *
    class ReadSchema:
    print PropertyReader().readProperty('source1_section','source_name1')
    print PropertyReader().readProperty('source2_section','sn2_sc1_tb')
    

    Content of .properties file:

    [source1_section]
    source_name1:module1
    sn1_schema:schema1,schema2,schema3
    sn1_sc1_tb:employee,department,location
    sn1_sc2_tb:student,college,country
    [source2_section]