我需要能够使用它ConfigParser来读取同一个键的多个值.示例配置文件:
[test]
foo = value1
foo = value2
xxx = yyy
Run Code Online (Sandbox Code Playgroud)
使用"标准"使用时ConfigParser,将有一个foo具有该值的键value2.但我需要解析器读入两个值.
在重复键上输入后,我创建了以下示例代码:
from collections import OrderedDict
from ConfigParser import RawConfigParser
class OrderedMultisetDict(OrderedDict):
def __setitem__(self, key, value):
try:
item = self.__getitem__(key)
except KeyError:
super(OrderedMultisetDict, self).__setitem__(key, value)
return
print "item: ", item, value
if isinstance(value, list):
item.extend(value)
else:
item.append(value)
super(OrderedMultisetDict, self).__setitem__(key, item)
config = RawConfigParser(dict_type = OrderedDict)
config.read(["test.cfg"])
print config.get("test", "foo")
print config.get("test", "xxx")
config2 = RawConfigParser(dict_type = OrderedMultisetDict)
config2.read(["test.cfg"])
print …Run Code Online (Sandbox Code Playgroud) ConfigParser要求所有部分,键和值都是字符串; 没有惊喜.它的方法来将值转换为数据类型有getfloat,getint,getboolean.如果你不知道的数据类型,你可以包装get()与eval()获得有评估,如字符串:
>>> from ConfigParser import SafeConfigParser
>>> cp = SafeConfigParser()
>>> cp.add_section('one')
>>> cp.set('one', 'key', '42')
>>> print cp.get('one', 'key')
'42'
>>> print eval(cp.get('one', 'key'))
42
>>> cp.set('one', 'key', 'None')
>>> print eval(cp.get('one', 'key'))
None
>>>
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?我认为在评估文件中的文本方面存在一些严重的安全问题 - 我承认这一点; 我完全信任该文件.
我以为我会用pickle它,但我真的想保持配置文件是人类可读的.
你会怎么做?
我收到ConfigParser.NoSectionError:没有部分:使用上面的代码'TestInformation'错误.
def LoadTestInformation(self):
config = ConfigParser.ConfigParser()
print(os.path.join(os.getcwd(),'App.cfg'))
with open(os.path.join(os.getcwd(),'App.cfg'),'r') as configfile:
config.read(configfile)
return config.items('TestInformation')
Run Code Online (Sandbox Code Playgroud)
文件路径是正确的,我已经双重检查.并且配置文件具有TestInformation部分
[TestInformation]
IEPath = 'C:\Program Files\Internet Explorer\iexplore.exe'
URL = 'www.google.com.au'
'''date format should be '<Day> <Full Month> <Full Year>'
SystemDate = '30 April 2013'
Run Code Online (Sandbox Code Playgroud)
在app.cfg文件中.不确定我做错了什么
Python中的ConfigParser文档讲述了很多关于所谓的"魔法插值"功能,但从未解释它实际上做了什么.我试过搜索它,但没有找到任何答案.
我尝试解析文件,如:
[account]
User = first
[account]
User = second
Run Code Online (Sandbox Code Playgroud)
我在Python中使用ConfigParser,但是当我读取文件时:
Config = configparser.ConfigParser()
Config.read(file)
print (Config.sections())
Run Code Online (Sandbox Code Playgroud)
我有错误:
While reading from ... : section 'account' already exists
Run Code Online (Sandbox Code Playgroud)
我该如何解析这个文件?还有其他图书馆吗?(更喜欢python3)
我的配置文件中有这样的东西(包含字符串列表的配置选项):
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
Run Code Online (Sandbox Code Playgroud)
是否有更优雅(内置)的方法从filtersToCheck获取列表而不是删除括号,单引号,空格然后使用split()它?也许一个不同的模块?
(使用python3.)
我有配置文件,
[local]
variable1 : val1 ;#comment1
variable2 : val2 ;#comment2
Run Code Online (Sandbox Code Playgroud)
像这样的代码只读取键的值:
class Config(object):
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.config.read('config.py')
def get_path(self):
return self.config.get('local', 'variable1')
if __name__ == '__main__':
c = Config()
print c.get_path()
Run Code Online (Sandbox Code Playgroud)
但我也想阅读评论以及价值,这方面的任何建议都会非常有帮助.
是否可以使用缩进使用 Python 'configparser' 存储多维字典(3 深)?解决方法是拆分键值,但想知道是否有一种干净的方法可以直接导入字典。
不起作用 - 在 CONFIGPARSER 中使用子选项缩进
[选项]
[子选项]
选项 1 = 值 1
选项 2 = 值 2
选项 3 = 值 3
作品 - 拆分用于子选项值
[选项]
SUB-OPTION = 'option1, value1',
'选项2,值2',
'选项3,值3'
字典值
dict['OPTIONS']['SUB-OPTION'] = {
选项1:值1,
选项2:值2,
选项3:值3,
}
我试图将 configparser 和 argparse 结合起来用于脚本,以便 argparse 定义的各种参数的默认值存储在通过 configparser 操作的配置文件中。我遇到的问题是布尔选项。argparse 具有这些选项的store_true和store_false操作,它们会自动创建默认值并指定给定选项时要更改的内容。但是,由于默认值是从配置文件中读取的,因此我不知道要提前做什么才能使用这些操作。这会建议类似:
import argparse,configparser
config = configparser.ConfigParser()
config['DEFAULT']['test'] = 'False'
config.read('testing.cfg')
parser = argparse.ArgumentParser()
if config.getboolean('DEFAULT','test'):
parser.add_argument('-t',action='store_false', dest='test')
else:
parser.add_argument('-t',action='store_true', dest='test')
args = parser.parse_args()
print(args.test)
Run Code Online (Sandbox Code Playgroud)
parser.addargument但是,我不喜欢在条件中包含语句的想法(尤其是我拥有的这些选项越多,就越麻烦)。我更喜欢的是这样的:
parser.add_argument('-t',action='toggle_boolean',dest='test',default=config.getboolean('DEFAULT','test'))
Run Code Online (Sandbox Code Playgroud)
在这种情况下,toggle_boolean当给出参数时,该操作将切换布尔值的状态,无论它是什么。问题是所述操作 ( toggle_boolean) 不存在。我将如何定义这样的操作,或者是否有更好的方法来做到这一点?
我跑去aws configure设置我的访问密钥 ID 和秘密访问密钥。这些现在存储在~/.aws/credentials其中看起来像:
[default]
aws_access_key_id = ######
aws_secret_access_key = #######
Run Code Online (Sandbox Code Playgroud)
我正在尝试访问我正在使用 configparser 编写的脚本的这些键。这是我的代码:
import configparser
def main():
ACCESS_KEY_ID = ''
ACCESS_SECRET_KEY = ''
config = configparser.RawConfigParser()
print (config.read('~/.aws/credentials')) ## []
print (config.sections()) ## []
ACCESS_KEY_ID = config.get('default', 'aws_access_key_id') ##configparser.NoSectionError: No section: 'default'
print(ACCESS_KEY_ID)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我使用python3 script.py. 关于这里发生了什么的任何想法?似乎 configparser 根本没有读取/查找文件。
configparser ×10
python ×10
python-3.x ×3
argparse ×1
dictionary ×1
eval ×1
list ×1
python-2.7 ×1