149

次の形式(.propertiesまたは.ini)が与えられます。

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

Javaの場合、上記の形式を解析/操作する機能を提供するPropertiesクラスがあります。

Python標準ライブラリ(2.x)に似たようなものはありますか?

そうでない場合、他にどのような選択肢がありますか?

4

25 に答える 25

86

私はこれを動作させることができましたが、これConfigParserを行う方法の例は誰も示していませんでした。そこで、プロパティファイルの簡単なPythonリーダーとプロパティファイルの例を示します。拡張子はまだ.propertiesですが、.iniファイルに表示されるものと同様のセクションヘッダーを追加する必要がありました...少しろくでなしですが、機能します。

Pythonファイル: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をご覧ください。

于 2014-10-06T16:59:40.040 に答える
74

.iniファイルの場合、ファイルconfigparserと互換性のある形式を提供するモジュールがあり.iniます。

とにかく、完全なファイルを解析するために利用できるものは何もありません.properties。それをしなければならないときは、単にjythonを使用します(スクリプトについて話している)。

于 2010-08-29T15:39:56.700 に答える
67

これは非常に古い質問であることは知っていますが、今必要なので、ほとんどのユースケース(すべてではない)をカバーする独自のソリューションである純粋な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" }
于 2015-08-06T09:47:06.277 に答える
64

Javaプロパティファイルは、多くの場合、有効なPythonコードでもあります。myconfig.propertiesファイルの名前をmyconfig.pyに変更できます。次に、このようにファイルをインポートします

import myconfig

プロパティに直接アクセスします

print myconfig.propertyName1
于 2011-11-22T01:13:13.900 に答える
17

ファイル形式のオプションがある場合は、前述のように.iniとPythonのConfigParserを使用することをお勧めします。Java .propertiesファイルとの互換性が必要な場合は、jpropsというライブラリを作成しました。pyjavapropertiesを使用していましたが、さまざまな制限に遭遇した後、自分で実装することになりました。ユニコードのサポートやエスケープシーケンスのサポートなど、.properties形式を完全にサポートしています。Jpropsはファイルのようなオブジェクトを解析することもできますが、pyjavapropertiesはディスク上の実際のファイルでのみ機能します。

于 2011-11-30T01:16:25.880 に答える
16

複数行のプロパティがなく、非常に単純なニーズがある場合は、数行のコードで解決できます。

ファイル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}
于 2018-07-10T10:47:20.887 に答える
6

これは正確にはプロパティではありませんが、Pythonには構成ファイルを解析するための優れたライブラリがあります。このレシピも参照してください:java.util.PropertiesのPython置換

于 2010-08-29T15:38:43.990 に答える
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'
于 2019-02-12T23:02:59.130 に答える
4

これが私のプロジェクトへのリンクです:https ://sourceforge.net/projects/pyproperties/ 。これは、Python3.xの*.propertiesファイルを操作するためのメソッドを備えたライブラリです。

ただし、java.util.Propertiesに基づいていません

于 2012-10-28T20:51:11.820 に答える
3

これは、java.util.Propetiesを1対1で置き換えたものです。

ドキュメントから:

  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.
于 2011-06-29T21:35:16.020 に答える
3

プロパティファイルのセクションからすべての値を簡単な方法で読み取る必要がある場合:

あなたの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']

設定ファイルからそのセクションを1回だけ読み取るメソッドにすべてを入れます(プログラムの実行中にメソッドが最初に呼び出されたとき)。

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​​」の下のキーです。)

于 2017-01-17T09:32:41.610 に答える
3

ここで定義されているファイルのようなオブジェクトを使用できます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()
于 2017-05-18T03:19:59.600 に答える
3

Pythonモジュールに辞書を作成し、それにすべてを保存してアクセスします。次に例を示します。

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

これでアクセスするには、次のようにするだけです。

submitButton = driver.find_element_by_id(dict['elementID'])
于 2019-06-18T16:18:25.853 に答える
3

私のJavainiファイルにはセクションヘッダーがなく、結果としてdictが必要でした。だから私は単に「[ini]」セクションを挿入し、デフォルトの設定ライブラリにその仕事をさせました。

例として、EclipseIDE.metadataディレクトリのversion.inifieを取り上げます。

#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
于 2020-11-01T10:09:01.873 に答える
2

これが私のプロジェクトで行っていることです。プロジェクトで使用したすべての一般的な変数/プロパティを含むproperties.pyという別の.pyファイルを作成するだけです。どのファイルでも、これらの変数を参照する必要があります。

from properties import *(or anything you need)

この方法を使用して、開発場所を頻繁に変更し、いくつかの一般的な変数がローカル環境にかなり関連しているときに、svnの平和を維持しました。私にとっては問題なく動作しますが、この方法が正式な開発環境などに推奨されるかどうかはわかりません。

于 2012-12-12T05:30:14.103 に答える
2

JavaのPropertiesクラスにほぼ類似したPythonモジュールを作成しました(実際には、SpringのPropertyPlaceholderConfigurerに似ており、$ {variable-reference}を使用して定義済みのプロパティを参照できます)。

編集:コマンドを実行してこのパッケージをインストールできます(現在、Python 3でテストされています)。
pip install property

プロジェクトはGitHubでホストされています

例:(詳細なドキュメントはここにあります)

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')
于 2016-05-28T18:39:49.400 に答える
2
import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)

test.jsonの内容:{"host": "127.0.0.1"、 "user": "jms"}

于 2016-06-02T16:27:00.753 に答える
1

以下の2行のコードは、Pythonリスト内包表記を使用して「javastyle」プロパティファイルをロードする方法を示しています。

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/

于 2017-07-27T20:28:14.403 に答える
1

パラメータ「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)

設定ファイル

--a
hello
--b
hello dear

コマンドを実行

python temp.py "#config"
于 2020-05-12T16:57:14.777 に答える
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
于 2015-06-11T15:09:31.167 に答える
0

これは私がファイルを解析し、コメントをスキップする環境変数として設定し、hg:dを指定するためにスイッチを追加したものです。

  • -hまたは--help使用状況の概要を印刷する
  • -cコメントを識別する文字を指定します
  • -sプロップファイルのキーと値の間のセパレータ
  • 解析する必要のあるプロパティファイルを指定します。例: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))))
    
    
    
    
    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:])
    
于 2016-09-01T09:40:32.637 に答える
0

Lightbendは、プロパティファイルといくつかのJSONベースの拡張機能を解析するTypesafeConfigライブラリをリリースしました。LightbendのライブラリはJVM専用ですが、広く採用されているようで、Pythonを含む多くの言語のポートがあります:https ://github.com/chimpler/pyhocon

于 2018-05-01T22:42:50.933 に答える
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
于 2018-11-01T14:04:52.573 に答える
0

これは私のために働きます。

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']
于 2019-02-12T22:56:42.867 に答える
0

私はconfigparserのアプローチに従いましたが、それは私にとって非常にうまくいきました。1つのPropertyReaderファイルを作成し、そこでconfigパーサーを使用して、各セクションに対応するプロパティを準備しました。

**使用されたPython2.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')

.propertiesファイルの内容:

[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
于 2019-02-24T14:25:40.470 に答える