17

モジュールを使用ConfigParserする場合、cfg ファイルに設定された複数の単語を含む値を使用したいと考えています。example.cfgこの場合、文字列を ( )のような引用符で囲むのは些細なことのように思えます。

[GENERAL]
onekey = "value in some words"

私の問題は、この場合、次のような値を使用すると、python が文字列にも引用符を追加することです。

config = ConfigParser()
config.read(["example.cfg"])
print config.get('GENERAL', 'onekey')

'value in some words'の代わりに印刷のみを管理する組み込み機能があると確信しています'"value in some words"'。それはどのように可能ですか?ありがとう。

4

8 に答える 8

14

configparser のマニュアルには何も記載されていませんが、文字列のメソッドを使用して.strip、先頭と末尾の二重引用符を取り除くことができます。

>>> s = '"hello world"'
>>> s
'"hello world"'
>>> s.strip('"')
'hello world'
>>> s2 = "foo"
>>> s2.strip('"')
'foo'

ご覧のとおり.strip、指定された文字列で開始および終了しない場合、 は文字列を変更しません。

于 2009-08-21T11:17:38.490 に答える
8
import ConfigParser

class MyConfigParser(ConfigParser.RawConfigParser):
    def get(self, section, option):
        val = ConfigParser.RawConfigParser.get(self, section, option)
        return val.strip('"')

if __name__ == "__main__":
    #config = ConfigParser.RawConfigParser()
    config = MyConfigParser()

    config.read(["example.cfg"])
    print config.get('GENERAL', 'onekey') 
于 2010-02-01T12:23:03.370 に答える
5

申し訳ありませんが、解決策も簡単でした。引用符を残すだけで、Pythonは等号の右側をとるだけのようです。

于 2009-08-21T11:21:07.360 に答える
3

質問はすでにかなり古いですが、少なくとも 2.6 では、スペースが保持されるため、引用符を使用する必要はありません。

from ConfigParser import RawConfigParser
from StringIO import StringIO

s = RawConfigParser()
s.readfp(StringIO('[t]\na= 1 2 3'))
s.get('t','a')
> '1 2 3'

ただし、先頭または末尾のスペースには当てはまりません! それらを保持したい場合は、それらを引用符で囲み、提案どおりに進める必要があります。eval大きなセキュリティ ホールが発生するため、キーワードの使用は控えてください。

于 2012-12-07T09:54:48.357 に答える
0

私は同じ問題に直面しなければなりませんでした。configparser オブジェクトの代わりに、通常の辞書を使用することを好みます。そのため、最初にファイルを読み取り.ini、次に configparser オブジェクトを dict に変換し、最後に文字列値から引用符 (またはアポストロフィ) を削除します。これが私の解決策です:

設定.ini

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'

たとえば .py

#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences("preferences.ini")
d = prefs.as_dict()
pprint(d)

設定.py

import sys
import configparser
import json
from pprint import pprint

def remove_quotes(original):
    d = original.copy()
    for key, value in d.items():
        if isinstance(value, str):
            s = d[key]
            if s.startswith(('"', "'")):
                s = s[1:]
            if s.endswith(('"', "'")):
                s = s[:-1]
            d[key] = s
            # print(f"string found: {s}")
        if isinstance(value, dict):
            d[key] = remove_quotes(value)
    #
    return d

class Preferences:
    def __init__(self, preferences_ini):
        self.preferences_ini = preferences_ini

        self.config = configparser.ConfigParser()
        self.config.read(preferences_ini)

        self.d = self.to_dict(self.config._sections)

    def as_dict(self):
        return self.d

    def to_dict(self, config):
        """
        Nested OrderedDict to normal dict.
        Also, remove the annoying quotes (apostrophes) from around string values.
        """
        d = json.loads(json.dumps(config))
        d = remove_quotes(d)
        return d

d = remove_quotes(d)は、引用符を削除する責任があります。違いを確認するには、この行をコメント化またはコメント解除してください。

出力:

$ ./example.py

{'GENERAL': {'onekey': 'value in some words'},
 'SETTINGS': {'resolution': '1024 x 768'}}
于 2018-06-09T09:16:12.693 に答える
-3

この場合、最も簡単な解決策は「eval()」です。

ただし、セキュリティについて心配するかもしれませんが、次の方法でこれを行うことができます。

def literal_eval(node_or_string):
    """
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts,booleans,
    and None.
    """

サンプルとして:

import ast
config = ConfigParser()
config.read(["example.cfg"])
print ast.literal_eval(config.get('GENERAL', 'onekey'))
# value in some words
于 2015-11-16T07:11:07.577 に答える