Python ConfigParser - 引号之间的值

发布于 2024-08-02 02:36:03 字数 430 浏览 11 评论 0原文

使用 ConfigParser 模块时,我想使用包含 cfg 文件中设置的多个单词的值。 在这种情况下,对我来说,用引号引起来的字符串似乎很简单(example.cfg):

[GENERAL]
onekey = "value in some words"

我的问题是,在这种情况下,python 在使用如下值时也会将引号附加到字符串中:

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

我确信有一个内置功能可以仅打印'某些单词中的值'而不是'“某些单词中的值”'。 这怎么可能? 谢谢。

When using ConfigParser module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (example.cfg):

[GENERAL]
onekey = "value in some words"

My problem is that in this case python appends the quotes to the string as well when using the value like this:

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

I am sure there is an in-built feature to manage to print only 'value in some words' instead of '"value in some words"'. How is it possible? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

秋风の叶未落 2024-08-09 02:36:03

我在 configparser 手册 中没有看到任何内容,但您可以使用.strip 方法去除前导和尾随双引号。

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

正如您所看到的,如果 .strip 不以指定字符串开头和结尾,则不会修改该字符串。

I didn't see anything in the configparser manual, but you could just use the .strip method of strings to get rid of the leading and trailing double quotes.

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

As you can see, .strip does not modify the string if it does not start and end with the specified string.

东走西顾 2024-08-09 02:36:03
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') 
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') 
触ぅ动初心 2024-08-09 02:36:03

抱歉,解决方案也很简单 - 我可以简单地留下引号,看起来 python 只是采用等号的右侧。

Sorry, the solution was trivial as well - I can simply leave the quotes, it looks python simply takes the right side of equal sign.

π浅易 2024-08-09 02:36:03

这个问题已经很老了,但在 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 关键字,因为这会带来巨大的安全漏洞。

The question is quite old already, but in 2.6 at least you don't need to use quotes as spaces are retained.

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'

That doesn't apply though either to leading or trailing spaces! If you want to retain those, you will need to enclose them in quotes an proceed as suggested. Refrain from using the eval keyword as you'll have a huge security hole.

莫相离 2024-08-09 02:36:03

可以编写如下配置读取函数,以字典形式返回配置。

def config_reader():
"""
Reads configuration from configuration file.
"""
configuration = ConfigParser.ConfigParser()
configuration.read(__file__.split('.')[0] + '.cfg')
config = {}
for section in configuration.sections():
    config[section] = {}
    for option in configuration.options(section):
        config[section][option] = (configuration.get(section, option)).strip('"').strip("'")
return config

can write configuration reading function as follows, which returns configuration in dictionary form.

def config_reader():
"""
Reads configuration from configuration file.
"""
configuration = ConfigParser.ConfigParser()
configuration.read(__file__.split('.')[0] + '.cfg')
config = {}
for section in configuration.sections():
    config[section] = {}
    for option in configuration.options(section):
        config[section][option] = (configuration.get(section, option)).strip('"').strip("'")
return config
阳光下的泡沫是彩色的 2024-08-09 02:36:03

戴维,

正如你所说,你可以把引号从字符串中去掉。

对于我正在从事的一个项目,我希望能够将几乎任何 Python 字符串文字表示为我的一些配置选项的值,更重要的是我希望能够将其中一些作为原始字符串文字处理。 (我希望该配置能够处理 \n、\x1b 等内容)。

在这种情况下,我使用了类似:

def EvalStr(s, raw=False):
    r'''Attempt to evaluate a value as a Python string literal or
       return s unchanged.

       Attempts are made to wrap the value in one, then the 
       form of triple quote.  If the target contains both forms
       of triple quote, we'll just punt and return the original
       argument unmodified.

       Examples: (But note that this docstring is raw!)
       >>> EvalStr(r'this\t is a test\n and only a \x5c test')
       'this\t is a test\n and only a \\ test'

       >>> EvalStr(r'this\t is a test\n and only a \x5c test', 'raw')
       'this\\t is a test\\n and only a \\x5c test'
    '''

    results = s  ## Default returns s unchanged
    if raw:
       tmplate1 = 'r"""%s"""'
       tmplate2 = "r'''%s'''"
    else:
       tmplate1 = '"""%s"""'
       tmplate2 = "'''%s'''"

    try:
       results = eval(tmplate1 % s)
     except SyntaxError:
    try:
        results = eval(tmplate2 %s)
    except SyntaxError:
        pass
    return results

... 我认为它可以处理不包含三重单引号和三重双引号字符串的任何内容。

(这一极端情况远远超出了我的要求)。

这段代码有一个奇怪的地方: 语法荧光笔似乎被混淆了
事实上,我的文档字符串是一个原始字符串。 这是让 doctest 满意这个特定功能所必需的)。

Davey,

As you say you can just leave the quotes off your string.

For a project I'm working on I wanted to be able to represent almost any Python string literal as a value for some of my config options and more to the point I wanted to be able to handle some of them as raw string literals. (I want that config to be able to handle things like \n, \x1b, and so on).

In that case I used something like:

def EvalStr(s, raw=False):
    r'''Attempt to evaluate a value as a Python string literal or
       return s unchanged.

       Attempts are made to wrap the value in one, then the 
       form of triple quote.  If the target contains both forms
       of triple quote, we'll just punt and return the original
       argument unmodified.

       Examples: (But note that this docstring is raw!)
       >>> EvalStr(r'this\t is a test\n and only a \x5c test')
       'this\t is a test\n and only a \\ test'

       >>> EvalStr(r'this\t is a test\n and only a \x5c test', 'raw')
       'this\\t is a test\\n and only a \\x5c test'
    '''

    results = s  ## Default returns s unchanged
    if raw:
       tmplate1 = 'r"""%s"""'
       tmplate2 = "r'''%s'''"
    else:
       tmplate1 = '"""%s"""'
       tmplate2 = "'''%s'''"

    try:
       results = eval(tmplate1 % s)
     except SyntaxError:
    try:
        results = eval(tmplate2 %s)
    except SyntaxError:
        pass
    return results

... which I think will handle anything that doesn't contain both triple-single and triple-double quoted strings.

(That one corner case is way beyond my requirements).

There is an oddity of this code here on SO; the Syntax highlighter seems to be confused by
the fact that my docstring is a raw string. That was necessary to make doctest happy for this particular function).

秉烛思 2024-08-09 02:36:03

我不得不面对同样的问题。 我更喜欢使用普通字典,而不是 configparser 对象。 因此,首先我读取 .ini 文件,然后将 configparser 对象转换为 dict,最后从字符串值中删除引号(或撇号)。 这是我的解决方案:

preferences.ini

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'

example.py

#!/usr/bin/env python3

from pprint import pprint
import preferences

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

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

I had to face the same problem. Instead of a configparser object, I prefer to work with normal dictionaries. So first I read the .ini file, then convert the configparser object to dict, and finally I remove quotes (or apostrophes) from string values. Here is my solution:

preferences.ini

[GENERAL]
onekey = "value in some words"

[SETTINGS]
resolution = '1024 x 768'

example.py

#!/usr/bin/env python3

from pprint import pprint
import preferences

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

preferences.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

The line d = remove_quotes(d) is responsible for removing the quotes. Comment / uncomment this line to see the difference.

Output:

$ ./example.py

{'GENERAL': {'onekey': 'value in some words'},
 'SETTINGS': {'resolution': '1024 x 768'}}
2024-08-09 02:36:03

在这种情况下,最简单的解决方案是“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

At this situation, the most simple solution is "eval()".

However, you may worry about the security stuff.But you could still do this by:

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.
    """

as a sample:

import ast
config = ConfigParser()
config.read(["example.cfg"])
print ast.literal_eval(config.get('GENERAL', 'onekey'))
# value in some words
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文