代码之家  ›  专栏  ›  技术社区  ›  Andrei Ciobanu

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

  •  114
  • Andrei Ciobanu  · 技术社区  · 14 年前

    .属性 .ini文件

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

    为了 Properties 类,该类提供解析上述格式或与之交互的功能。

    这里面有相似的东西吗 python 标准 图书馆(2.x)?

    如果没有,我还有别的选择吗?

    22 回复  |  直到 10 年前
        1
  •  70
  •   pygabriel    14 年前

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

        2
  •  79
  •   James Oravec    10 年前

    我能让这个工作 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

        3
  •  65
  •   Travis Bear    12 年前

    java属性文件通常也是有效的python代码。你可以重新命名你的myconfig.properties属性文件到myconfig.py公司. 然后像这样导入你的文件

    import myconfig
    

    print myconfig.propertyName1
    
        4
  •  65
  •   Roberto    8 年前

    我知道这是一个非常老的问题,但我现在需要它,我决定实现我自己的解决方案,一个纯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" }
    
        5
  •  17
  •   Matt Good    13 年前

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

        6
  •  15
  •   mvallebr    7 年前

    文件 t.properties

    a=b
    c=d
    e=f
    

    Python代码:

    with open("t.properties") as f:
        l = [line.split("=") for line in f.readlines()]
        d = {key.strip(): value.strip() for key, value in l}
    
        7
  •  6
  •   Manoj Govindan    14 年前

    nice library 用于解析配置文件。另请参阅以下配方: A python replacement for java.util.Properties .

        8
  •  4
  •   marekjm    12 年前

    以下是我的项目链接: https://sourceforge.net/projects/pyproperties/

    但这不是基于java.util.Properties属性

        9
  •  4
  •   Andy Quiroz    6 年前

    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'
    
        10
  •  3
  •   tmow    14 年前

    This

    从文件中:

      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.
    
        11
  •  3
  •   Alexander Pogrebnyak    8 年前

    您可以在中使用类似文件的对象 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()
    
        12
  •  3
  •   MANU    6 年前

    如果需要以简单的方式读取属性文件中某节的所有值:

    config.properties 文件布局:

    [SECTION_NAME]  
    key1 = value1  
    key2 = value2  
    

    您的代码:

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

    现在要获取key1的值: details_dict['key1']

    把它放在一个只从配置文件中读取该节一次的方法中(在程序运行期间第一次调用该方法)。

    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'] 
    

    “port”是“DB”节下的键。)

        13
  •  2
  •   festony    12 年前

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

    from properties import *(or anything you need)
    

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

        14
  •  2
  •   user1261273 user1261273    9 年前
    import json
    f=open('test.json')
    x=json.load(f)
    f.close()
    print(x)
    

    的内容测试.json: {“host”:“127.0.0.1”,“user”:“jms”}

        15
  •  2
  •   Anand Joshi    8 年前

    我创建了一个python模块,它几乎类似于Java的Properties类(实际上它类似于spring中的PropertyPlaceholderConfigurer,它允许您使用${variable reference}引用已经定义的属性)

    EDIT:您可以通过运行命令(当前已针对python3进行了测试)来安装此软件包。
    pip install property

    GitHub

    示例:(可以找到详细的文档 here

    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')
    
        16
  •  2
  •   Vineet Singh    6 年前

    在python模块中创建一个字典,并将所有内容存储到其中并访问它,例如:

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

    现在要访问它,您只需执行以下操作:

    submitButton = driver.find_element_by_id(dict['elementID'])
    
        17
  •  1
  •   Anoop Isaac    7 年前

    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/

        18
  •  1
  •   Jeremy Caney Abloin    5 年前

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

    配置文件

    --a
    hello
    --b
    hello dear
    

    python temp.py "#config"
    
        19
  •  1
  •   Wolfgang Fahl    4 年前

    我的javaini文件没有节头,因此我想要一个dict。所以我只注入了一个“[ini]”部分,让默认的配置库完成它的工作。结果转换为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
    
        20
  •  0
  •   narko    10 年前

    我使用ConfigParser实现了这一点,如下所示。代码假定有一个名为配置属性在放置BaseTest的同一目录中:

    配置属性

    [CredentialSection]
    app.name=MyAppName
    

    基本测试.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
    
        21
  •  0
  •   patel    8 年前

    这就是我编写的解析文件并将其设置为env变量的内容,该变量跳过注释和添加的非键值行开关来指定 汞:d

    • -h或--帮助打印使用情况摘要
    • -c指定标识注释的字符
    • 并指定需要解析的属性文件,例如:python

      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:])
      
        22
  •  0
  •   DGrady    7 年前

    Typesafe Config 库,它解析属性文件和一些基于JSON的扩展。Lightbend的库只针对JVM,但它似乎被广泛采用,现在有许多语言的端口,包括Python: https://github.com/chimpler/pyhocon

        23
  •  0
  •   Memin    6 年前

    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
    
        24
  •  0
  •   Andy Quiroz    6 年前

    这对我有用。

    from pyjavaproperties import Properties
    p = Properties()
    p.load(open('test.properties'))
    p.list()
    print p
    print p.items()
    print p['name3']
    
        25
  •  0
  •   Vaibhav Shukla    6 年前

    我遵循configparser方法,对我来说效果很好。创建了一个PropertyReader文件,并在其中使用配置解析器来准备对应于每个节的属性。

    **使用Python 2.7

    的内容属性reader.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')
    

    [source1_section]
    source_name1:module1
    sn1_schema:schema1,schema2,schema3
    sn1_sc1_tb:employee,department,location
    sn1_sc2_tb:student,college,country
    
    [source2_section]
    source_name1:module2
    sn2_schema:schema4,schema5,schema6
    sn2_sc1_tb:employee,department,location
    sn2_sc2_tb:student,college,country