简体   繁体   English

创建适合Python和Java的配置文件的“标准”方法

[英]“Standard” way of creating config file suitable for Python and Java together

My application was 100% developed in pure Python. 我的应用程序是100%用纯Python开发的。 I found very useful and easy to create a config file with .py extension and than simply load it in every code. 我发现非常有用且易于创建扩展名为.py的配置文件,而不是简单地在每个代码中加载它。 Something like this: 像这样的东西:

ENV = 'Dev'
def get_settings():
    return eval(ENV)

class Dev():
    ''' Development Settings '''

    # AWS settings
    aws_key = 'xxxxxxxxxxxxx'
    aws_secret = 'xxxxxxxxxxxxxxxxx'

    # S3 settings
    s3_bucket = 'xxxxxxxxxx'
    ...
    ...

And than in my code I just import this file and use settings, this way I have one file that easy to manage and that contains all aprameters I need. 而且在我的代码中我只导入此文件并使用设置,这样我就有一个易于管理的文件,其中包含我需要的所有参数。

Howewer recently I had to move part of my code to Java. 最近我不得不将部分代码移到Java上。 And now I'm struggling with configurations. 而现在我正在努力配置。

Question: 题:

What are the "standard" way to create a config that would be easily accessible from both languages? 创建可以从两种语言轻松访问的配置的“标准”方法是什么? (My Java skills are very limited, if you can five me a brief example in Java it would be great) (我的Java技能非常有限,如果你能用Java给我一个简单的例子那就太棒了)

Have a look at ConfigParser in Python 看看Python中的ConfigParser

The syntax on this file looks like this: 此文件的语法如下所示:

[Section]
my_option = 12.2
my_option2 = other_value

[Section2]
my_voption = my_value

You read it this way: 你这样读了:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')
config.getfloat('Section', 'my_option') # returns 12.2

It works for a couple of types and if you can't find a type, you can use the eval function in Python. 它适用于几种类型,如果找不到类型,可以在Python中使用eval函数。 Finding an equivalent to Java shouldn't be too hard. 找到与Java相当的东西应该不会太难。 Or even parsing this file using Java shouldn't be too hard. 甚至使用Java解析这个文件应该不会太难。

Use standard configuration files : XML or .properties for example. 使用标准配置文件:例如XML或.properties。

For XML, you can use JDOM in Java, minidom in Python. 对于XML,您可以在Java中使用JDOM ,在Python中使用minidom

For .properties, Java handles this nativaly via class Properties and Python can handle this via ConfigParser 对于.properties,Java通过类属性处理这个nativaly,Python可以通过ConfigParser处理它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM