python中的属性文件(类似于Java Properties)
给定以下格式(.properties 或 .ini):
propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN
对于 Java,有 Properties 类,提供解析/与上述格式交互的功能。
python 的 标准 库 (2.x) 中有类似的东西吗?
如果没有,我还有什么其他选择?
Given the following format (.properties or .ini):
propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN
For Java there is the Properties class that offers functionality to parse / interact with the above format.
Is there something similar in python's standard library (2.x) ?
If not, what other alternatives do I have ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
增强@mvallebr的非常好的答案:
Enhancing on the very good answer of @mvallebr:
尝试 ConfigParser
我能够让它与 ConfigParser 一起使用,没有人展示任何有关如何执行此操作的示例,因此这里是属性文件的简单 python 阅读器和属性文件的示例。请注意,扩展名仍然是
.properties
,但我必须添加一个类似于您在 .ini 文件中看到的节标题......有点混蛋,但它有效。python 文件:
PythonPropertyReader.py
属性文件:
ConfigFile.properties
有关更多功能,请阅读:https://docs.python.org/2/library/configparser.html
Try ConfigParser
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.The python file:
PythonPropertyReader.py
The property file:
ConfigFile.properties
For more functionality, read: https://docs.python.org/2/library/configparser.html
我知道这是一个非常老的问题,但我现在需要它,我决定实现我自己的解决方案,一个纯 python 解决方案,涵盖大多数用例(不是全部):
您可以更改
sep 到 ':' 以解析以下格式的文件:
代码正确解析如下行:
您将得到一个带有以下内容的字典:
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):
You can change the
sep
to ':' to parse files with format:The code parses correctly lines like:
You'll get a dict with:
对于
.ini
文件,有configparser
< /a> 模块,提供与.ini
文件兼容的格式。无论如何,没有任何东西可用于解析完整的
.properties
文件,当我必须这样做时,我只需使用 jython (我正在谈论脚本)。For
.ini
files there is theconfigparser
module that provides a format compatible with.ini
files.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).java 属性文件通常也是有效的 python 代码。您可以将 myconfig.properties 文件重命名为 myconfig.py。然后只需导入您的文件,就像这样
并直接访问属性
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
and access the properties directly
如果你没有多行属性并且需求非常简单,几行代码就可以为你解决:
文件
t.properties
:Python代码:
if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:
File
t.properties
:Python code:
如果您可以选择文件格式,我建议使用 .ini 和 Python 的 ConfigParser(如上所述)。如果您需要与 Java .properties 文件兼容,我已经为其编写了一个名为 jprops 的库。我们使用的是 pyjavaproperties,但在遇到各种限制后,我最终实现了自己的。它完全支持 .properties 格式,包括 unicode 支持和对转义序列的更好支持。 Jprops 还可以解析任何类似文件的对象,而 pyjavaproperties 仅适用于磁盘上的真实文件。
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.
我用过这个,这个库非常有用
i have used this, this library is very useful
这不完全是属性,但 Python 确实有一个用于解析配置文件的不错的库。另请参阅此食谱: A python replacement for java.util.Properties 。
This is not exactly properties but Python does have a nice library for parsing configuration files. Also see this recipe: A python replacement for java.util.Properties.
这是一个一对一的替换java.util.Propeties
来自文档:
This is a one-to-one replacement of java.util.Propeties
From the doc:
这是我的项目的链接:https://sourceforge.net/projects/pyproperties/。它是一个库,包含用于处理 Python 3.x 的 *.properties 文件的方法。
但它不是基于 java.util.Properties
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.
But it is not based on java.util.Properties
您可以在此处定义的 ConfigParser.RawConfigParser.readfp 中使用类似文件的对象 -> https://docs.python.org/2/library/ configparser.html#ConfigParser.RawConfigParser.readfp
定义一个覆盖
readline
的类,该类在属性文件的实际内容之前添加节名称。我已将其打包到返回所有已定义属性的
dict
的类中。You can use a file-like object in
ConfigParser.RawConfigParser.readfp
defined here -> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfpDefine a class that overrides
readline
that adds a section name before the actual contents of your properties file.I've packaged it into the class that returns a
dict
of all the properties defined.在 python 模块中创建一个字典,并将所有内容存储到其中并访问它,例如:
现在要访问它,您只需执行以下操作:
create a dictionary in your python module and store everything into it and access it, for example:
Now to access it you can simply do:
我的 Java ini 文件没有节标题,因此我想要一个字典。所以我只是注入了一个“[ini]”部分并让默认配置库完成其工作。
以eclipse IDE .metadata目录下的version.ini文件为例:
结果转换为dict:
My Java ini files didn't have section headers and I wanted a dict as a result. So i simply injected an "[ini]" section and let the default config library do its job.
Take a version.ini fie of the eclipse IDE .metadata directory as an example:
The result is converted to a dict:
这就是我在项目中所做的:我只是创建另一个名为properties.py的.py文件,其中包含我在项目中使用的所有常用变量/属性,并且在任何需要引用这些变量的文件中,放入
使用此方法当我经常更改开发位置并且一些常见变量与本地环境相当相关时,保持 svn 和平。对我来说效果很好,但不确定是否会建议这种方法用于正式的开发环境等。
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
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.
test.json的内容:
{“主机”:“127.0.0.1”,“用户”:“jms”}
Contents of test.json:
{"host": "127.0.0.1", "user": "jms"}
我创建了一个Python模块,它几乎类似于Java的Properties类(实际上它就像Spring中的PropertyPlaceholderConfigurer,它允许您使用${variable-reference}来引用已经定义的属性)
编辑:您可以通过以下方式安装这个包运行命令(当前针对 python 3 进行了测试)。
pip install property
该项目托管在 GitHub
示例:(详细文档可以可以在此处找到)
假设您在 my_file.properties 文件中定义了以下属性
加载上述属性的代码
I have created a python module that is almost similar to the Properties class of Java ( Actually it is like the PropertyPlaceholderConfigurer in spring which lets you use ${variable-reference} to refer to already defined property )
EDIT : You may install this package by running the command(currently tested for python 3).
pip install property
The project is hosted on GitHub
Example : ( Detailed documentation can be found here )
Let's say you have the following properties defined in my_file.properties file
Code to load the above properties
如果您需要以简单的方式读取属性文件中某个部分的所有值:
您的 config.properties 文件布局:
您编码:
这将为您提供一个字典,其中键与配置文件中的键相同,并且他们对应的值。
details_dict
是:现在获取 key1 的值:
details_dict['key1']
将其全部放入一个方法中,该方法仅从配置文件中读取该部分一次(在程序运行期间第一次调用该方法)。
现在调用上面的函数并获取所需键的值:
-------------------------------------- -----------------------
扩展上述方法,自动逐节读取,然后按节名加键名进行访问。
访问:
(此处“DB”是配置文件中的部分名称
并且“port”是“DB”部分下的键。)
If you need to read all values from a section in properties file in a simple manner:
Your
config.properties
file layout :You code:
This will give you a dictionary where keys are same as in config file and their corresponding values.
details_dict
is :Now to get key1's value :
details_dict['key1']
Putting it all in a method which reads that section from config file only once(the first time the method is called during a program run).
Now call the above function and get the required key's value :
-------------------------------------------------------------
Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.
To access:
(here 'DB' is a section name in config file
and 'port' is a key under section 'DB'.)
下面两行代码展示了如何使用Python列表理解来加载“java风格”属性文件。
详细请看下面的帖子
https:// /ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-compressive-and-generators/
Below 2 lines of code shows how to use Python List Comprehension to load 'java style' property file.
Please have a look at below post for details
https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/
您可以使用参数“fromfile_prefix_chars”和argparse从配置文件中读取,如下所示---
temp.py
配置文件
运行命令
you can use parameter "fromfile_prefix_chars" with argparse to read from config file as below---
temp.py
config file
Run command
您可以使用 - https://pypi.org/project/property/
例如 -
my_file.properties
代码
You could use - https://pypi.org/project/property/
eg -
my_file.properties
Code
这是我编写的用于解析文件并将其设置为环境变量的内容,该变量会跳过注释和非键值行添加的开关来指定
hg:d
并指定需要解析的属性文件 例如:python
EnvParamSet.py -c # -s = env.properties
This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify
hg:d
and specify properties file that needs to be parsed eg : python
EnvParamSet.py -c # -s = env.properties
Lightbend 发布了 Typesafe Config 库,它解析属性文件以及一些基于 JSON 的扩展。 Lightbend 的库仅适用于 JVM,但它似乎被广泛采用,并且现在有多种语言的移植,包括 Python:https://github.com/chimpler/pyhocon
Lightbend has released the Typesafe Config library, which parses properties files and also some JSON-based extensions. Lightbend's library is only for the JVM, but it seems to be widely adopted and there are now ports in many languages, including Python: https://github.com/chimpler/pyhocon
可以使用下面的函数,这是@mvallebr的修改代码。它尊重属性文件注释,忽略空新行,并允许检索单个键值。
You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.
这对我有用。
this works for me.
我遵循 configparser 方法,它对我来说效果很好。创建一个 PropertyReader 文件并在其中使用配置解析器来准备与每个部分相对应的属性。
**使用Python 2.7
PropertyReader.py 文件的内容:
读取模式文件的内容:
.properties 文件的内容:
I followed configparser approach and it worked quite well for me. Created one PropertyReader file and used config parser there to ready property to corresponding to each section.
**Used Python 2.7
Content of PropertyReader.py file:
Content of read schema file:
Content of .properties file:
您可以尝试 python-dotenv 库。该库从
.env
(因此不完全是.properties
文件)文件读取键值对,并可以将它们设置为环境变量。以下是官方文档中的示例用法:
You can try the
python-dotenv
library. This library reads key-value pairs from a.env
(so not exactly a.properties
file though) file and can set them as environment variables.Here's a sample usage from the official documentation:
我使用 ConfigParser 执行此操作,如下所示。该代码假设在放置
BaseTest.py
的同一目录中有一个名为config.prop
的文件:config.prop
:BaseTest.py
:I did this using ConfigParser as follows. The code assumes that there is a file called
config.prop
in the same directory whereBaseTest.py
is placed:config.prop
:BaseTest.py
: