Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ConfigParser-引号之间的值_Python_Configparser - Fatal编程技术网

Python ConfigParser-引号之间的值

Python ConfigParser-引号之间的值,python,configparser,Python,Configparser,当使用ConfigParser模块时,我希望使用包含cfg文件中设置的多个单词的值。在这种情况下,用(example.cfg)这样的引号将字符串括起来对我来说似乎很简单: 我的问题是,在这种情况下,python在使用如下值时也会将引号附加到字符串: config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') 我确信有一个内置功能可以管理只打印“某些单词中的值”,而不是打印“

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

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

config = ConfigParser()
config.read(["example.cfg"])
print config.get('GENERAL', 'onekey')
我确信有一个内置功能可以管理只打印
“某些单词中的值”
,而不是打印
“某些单词中的值”
。怎么可能呢?谢谢。

我在中没有看到任何内容,但是您可以使用字符串的
.strip
方法来消除前导和尾随双引号

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

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

对不起,解决方案也很简单-我可以简单地保留引号,看起来python只是取了等号的右边。

Davey

正如您所说,您可以将引号从字符串中去掉

对于我正在进行的项目,我希望能够将几乎所有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
。。。我认为它可以处理任何不同时包含三重单引号和三重双引号字符串的情况

(那个角落的箱子远远超出了我的要求)

在这里有一个奇怪的代码,所以;语法高亮显示程序似乎被
事实上,我的docstring是一个原始字符串。这个问题已经很老了,但在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
关键字,因为这样会有一个巨大的安全漏洞。

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

我不得不面对同样的问题。我更喜欢使用普通字典,而不是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)
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
首选项.py

#!/usr/bin/env python3

from pprint import pprint
import preferences

prefs = preferences.Preferences("preferences.ini")
d = prefs.as_dict()
pprint(d)
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'}}
可以编写如下配置读取函数,以字典形式返回配置。
注意最后一句应该更新<如果字符串以指定字符串开头或结尾,则代码>strip()会修改该字符串。e、 g.
“bar”。strip(“”)
返回
'bar
,而不是
bar
。我刚刚遇到了同样的问题,这确实是解决方案。即,更改为
[GENERAL]
onekey=value,在某些词中
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