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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3595363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:53:04  来源:igfitidea点击:

Properties file in python (similar to Java Properties)

pythonproperties

提问by Andrei Ciobanu

Given the following format (.propertiesor .ini):

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

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

For Javathere is the Propertiesclass that offers functionality to parse / interact with the above format.

对于Java,有一个Properties类提供解析/与上述格式交互的功能。

Is there something similar in python's standardlibrary (2.x) ?

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

If not, what other alternatives do I have ?

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

采纳答案by pygabriel

For .ini files there is the ConfigParsermodule that provides a format compatible with .ini files.

对于 .ini 文件,有提供与 .ini 文件兼容的格式的ConfigParser模块。

Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).

无论如何,没有什么可用于解析完整的 .properties 文件,当我必须这样做时,我只需使用 jython(我说的是脚本)。

回答by Manoj Govindan

This is not exactly properties but Python does have a nice libraryfor parsing configuration files. Also see this recipe: A python replacement for java.util.Properties.

这不完全是属性,但 Python 确实有一个很好的库来解析配置文件。另请参阅此秘籍:java.util.Properties 的 Python 替代品

回答by tmow

Thisis a one-to-one replacement of java.util.Propeties

是 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.

回答by Travis Bear

A java properties file is often valid python code as well. You could rename your myconfig.properties file to myconfig.py. Then just import your file, like this

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

import myconfig

and access the properties directly

并直接访问属性

print myconfig.propertyName1

回答by Matt Good

If you have an option of file formats I suggest using .ini and Python's ConfigParser as mentioned. If you need compatibility with Java .properties files I have written a library for it called jprops. We were using pyjavaproperties, but after encountering various limitations I ended up implementing my own. It has full support for the .properties format, including unicode support and better support for escape sequences. Jprops can also parse any file-like object while pyjavaproperties only works with real files on disk.

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

回答by marekjm

Here is link to my project: https://sourceforge.net/projects/pyproperties/. It is a library with methods for working with *.properties files for Python 3.x.

这是我的项目的链接:https: //sourceforge.net/projects/pyproperties/。它是一个包含用于处理 Python 3.x 的 *.properties 文件的方法的库。

But it is not based on java.util.Properties

但它不是基于 java.util.Properties

回答by festony

This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put

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

from properties import *(or anything you need)

Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.

当我经常更改开发位置并且一些常见变量与本地环境相当时,使用这种方法保持svn和平。对我来说很好用,但不确定这种方法是否适合正式的开发环境等。

回答by James Oravec

I was able to get this to work with ConfigParser, no one showed any examples on how to do this, so here is a simple python reader of a property file and example of the property file. Note that the extension is still .properties, but I had to add a section header similar to what you see in .ini files... a bit of a bastardization, but it works.

我能够使用它ConfigParser,没有人展示任何有关如何执行此操作的示例,因此这里是一个简单的属性文件的python阅读器和属性文件的示例。请注意,扩展名仍然是.properties,但我必须添加一个类似于您在 .ini 文件中看到的部分标题......有点混蛋,但它有效。

The python file: PythonPropertyReader.py

蟒蛇文件: 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

属性文件: ConfigFile.properties

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

For more functionality, read: https://docs.python.org/2/library/configparser.html

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

回答by narko

I did this using ConfigParser as follows. The code assumes that there is a file called config.prop in the same directory where BaseTest is placed:

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

config.prop

配置文件

[CredentialSection]
app.name=MyAppName

BaseTest.py:

基础测试.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

回答by Roberto

I know that this is a very old question, but I need it just now and I decided to implement my own solution, a pure python solution, that covers most uses cases (not all):

我知道这是一个非常古老的问题,但我现在需要它,我决定实现我自己的解决方案,一个纯 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

You can change the septo ':' to parse files with format:

您可以将 更改sep为 ':' 以解析具有以下格式的文件:

key : value

The code parses correctly lines like:

代码正确解析如下行:

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

You'll get a dict with:

你会得到一个字典:

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