标签: configparser

在Python ConfigParser中按字母顺序排序

是否有任何解决方案强制RawConfigParser.write()方法以字母顺序排序配置文件?

即使原始/加载的配置文件已排序,模块也会将部分和选项混合到各个部分中,并且非常讨厌手动编辑大量未排序的配置文件.

PD:我正在使用python 2.6

python configuration-files configparser

6
推荐指数
1
解决办法
3716
查看次数

在Python 2.7中手动构建ConfigParser的深层副本

刚开始我的Python学习曲线,并将一些代码移植到Python 2.7.看起来在Python 2.7中,不再可能对ConfigParser的实例执行deepcopy().似乎Python团队对恢复这样的功能并不十分感兴趣:

http://bugs.python.org/issue16058

有人可以提出一个优雅的解决方案来手动构建ConfigParser实例的深度复制/复制吗?

非常感谢,-Pete

deep-copy configparser python-2.7

6
推荐指数
2
解决办法
1573
查看次数

模拟方法调用Python

我一直在搜索堆栈交换和网络上如何做到这一点,但我无法理解如何模拟方法的行为.我正在尝试为自定义类模拟openpyxl行为和行为.这是我的尝试:

import unittest
from unittest.mock import MagicMock
import openpyxl 
from MyPythonFile import MyClass

class TestMyClass(unittest.TestCase):
  def test_myclass(self):
    myclass = MyClass()
    wb = openpyxl.workbook()
    ws = openpyxl.worksheet()
    wbPath = 'wbPath'

    openpyxl.load_workbook(wbPath, data_only = True) = MagicMock(return_value=wb)
Run Code Online (Sandbox Code Playgroud)

当我尝试最后一行时,我收到错误"无法分配给函数调用".我需要使用patch.object('openpyxl','load_workbook')吗?我习惯用Groovy在Java中进行模拟,而且非常简单.

*编辑:想要根据@alxwrd的响应添加测试的最终版本

import unittest
from unittest.mock import MagicMock
import openpyxl 
import configparser
from MyPythonFile import MyClass

class TestMyClass(unittest.TestCase):
  def test_myclass(self):
    myclass = MyClass()
    wb = openpyxl.workbook()
    ws = openpyxl.worksheet()
    config = configparser.ConfigParser()

    openpyxl.load_workbook = MagicMock(return_value=wb)
    wb.get_sheet_by_name = MagicMock(return_value=ws)

    config.sections() = MagicMock(return_value=['Section1'])
    config.get = …
Run Code Online (Sandbox Code Playgroud)

python methods unit-testing mocking configparser

6
推荐指数
2
解决办法
8468
查看次数

在database.ini文件中找不到节postgresql

我正在尝试在数据库(PostgreSQL 9.6)中创建表,并且当我启动python脚本这样做时,它返回以下类型的错误:

“在$ FILEDIR / database.ini文件中找不到节postgresql”

似乎解析器无法阅读本节,但我不明白为什么。

这是我的配置方法:

def config(filename='$FILEDIR/database.ini', section='postgresql'):

    parser = ConfigParser()
    parser.read(filename)

    db = {}

    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    return db
Run Code Online (Sandbox Code Playgroud)

Database.ini:

[postgresql]
host=localhost
database=mydatabase
user=myuser
password=mypassword
Run Code Online (Sandbox Code Playgroud)

我已经尝试了以下线程中的答案,但它完全没有帮助。有人知道原因吗?我使用的是python 2.7,并且已经执行了“ pip install config”和“ pip install configparser”的依赖项。

python configparser python-2.7

6
推荐指数
1
解决办法
1494
查看次数

如何在 Python 中加载配置文件并能够使用点表示法(属性)访问值?

我正在寻找一种解决方案,允许我使用配置文件数据的属性。

我希望能够做这样的事情:

config = Config('config.ini')
print config.section1.user
print config.section2.password
Run Code Online (Sandbox Code Playgroud)

我确实知道 ConfigParser 允许我做类似的事情,config['section1']['user']但这太丑陋了,我们不能做得更好吗?

该解决方案必须适用于 Python 2.5 或更高版本。

python ini configparser

5
推荐指数
1
解决办法
3796
查看次数

使用ConfigParser多次指定相同的选项

我想使用python ConfigParser模块读取配置文件:

[asection]
option_a = first_value
option_a = second_value
Run Code Online (Sandbox Code Playgroud)

我希望能够获得为选项“ option_a”指定的值的列表。我尝试了以下显而易见的方法:

test = """[asection]
option_a = first_value
option_a = second_value
"""
import ConfigParser, StringIO
f = StringIO.StringIO(test)
parser = ConfigParser.ConfigParser()
parser.readfp(f)
print parser.items()
Run Code Online (Sandbox Code Playgroud)

哪个输出:

[('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)

当我希望:

[('option_a', 'first_value'), ('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好:

[('option_a', ['first_value', 'second_value'])]
Run Code Online (Sandbox Code Playgroud)

有没有办法用ConfigParser做到这一点?另一个主意?

python configparser

5
推荐指数
1
解决办法
1064
查看次数

如何使 ConfigParser 返回默认值而不是引发 NoOptionError?

我有一个配置文件,其中定义了一些选项。有时,如果找不到请求的选项,我想忽略错误并返回None

setting.cfg

[Set]
ip=some_ip
verify=yes     #if verify does not exist here --> verify=None
Run Code Online (Sandbox Code Playgroud)

test.py

import sys
import ConfigParser

file="setting.cfg"

class ReadFile:
   def read_cfg_file(self):
      configParser = ConfigParser.RawConfigParser(allow_no_value=True)
      if os.path.isfile(file):
          configParser.read(file)
      else:
          sys.exit(1)
      try:
          verify = configParser.get('Set', 'verify')
      except ConfigParser.NoOptionError:
          pass

      return verify,and,lots,of,other,values
Run Code Online (Sandbox Code Playgroud)

如果我这样处理它,我将无法返回值,因为如果'verify'找不到该选项,它就会简单地传递。

如果找不到选项,有什么方法可以忽略错误,而是返回None

例如,这样的事情:

verify = configParser.get('Set', 'verify')
if not verify:
    verify=False
Run Code Online (Sandbox Code Playgroud)

python exception configparser python-2.7

5
推荐指数
2
解决办法
7582
查看次数

使用配置文件指定要在 Python 中执行的操作

我正在尝试使用配置文件、python 和 ConfigParser 构建动态操作。我对 Python 还很陌生(两周前),所以我不确定这是否可能,这就是我想问的原因。

这是一个示例配置文件:

[General]
Volume File = C:\Users\O\Desktop\Sanjeev\Python\Solution\volume.xlsx
New Variables File = C:\Users\O\Desktop\Sanjeev\Python\Solution\newvar.xlsx
Desired Variable Name = Price,Age
Merging Variables = Category,State
[Operations]
Operation1 = Price*Volume,Revenue
Operation2 = Revenue/Age,Annual Revenue
Run Code Online (Sandbox Code Playgroud)

因此,在这里我将使用合并变量来合并第一个和第二个数据集,保留并可能聚合所需的变量。然后,根据操作部分中指定的操作,我将执行它们并将它们存储在与列表中第二项同名的变量中。

我想在配置文件而不是 python 脚本中指定这些操作的原因是因为这些操作的数量和类型会有所不同。我需要创建动态代码,该代码能够解析配置文件中的此选项,就好像它是代码一样并执行它。

我想要一些关于如何开始的指导。

python config configuration-files configparser

5
推荐指数
1
解决办法
1678
查看次数

ConfigParser - 写入 .ini 文件

我有一个 config.ini 文件,其中包含 Web 应用程序的一些默认配置(使用 VS 2017 的 Flask)

我也想自己写一些配置。

我正在使用下面的代码尝试在该[keys]部分中写入,变量是gkey

def writeKey(key):
    Config = configparser.ConfigParser()    
    configFile = Path("config.ini")
    if configFile.is_file() == False:
        cfgfile = open("config.ini",'w')
    else:
        cfgfile = open("config.ini")

    # add the settings to the structure of the file, and lets write it out...
    Config.add_section('keys')
    Config.set('gkey','key',True)
    Config.write(cfgfile)
    cfgfile.close()

gkey = encrypt(key)
writeKey(gkey)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 59, in <module>
    writeKey(gkey)
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 30, in writeKey …
Run Code Online (Sandbox Code Playgroud)

python configparser flask

5
推荐指数
1
解决办法
1万
查看次数

python 3 和 python 2 中的 ConfigParser

我一直在慢慢地从 py2 -> py3 过渡,但我遇到了一个我无法完全解决的问题(尽管我确定问题是微不足道的)。当我执行下面的代码时,配置文件似乎没有任何部分:(

我哪里误会了?

请注意,我确实从 python 2 脚本中重用了这段代码(用新的 configparser.ConfigParser 替换了旧的 ConfigParser.SafeConfigParser)。我不认为这个事实是相关的,但也许是?显然,我不知道:)

这是项目/main.py

import inspect
import os
import utilities.utilities

def main():
    config_ini_path = os.path.abspath(inspect.getfile(inspect.currentframe()).split('.py')[0] + '_config.ini'
    print(config_ini_path)
    config = utilities.utilies.get_config(config_ini_path)
    print(config.sections())

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

这是项目/实用程序/实用程序.py:

import os
import configparser
import inspect
import sys

def get_config(config_file_path=os.path.abspath(inspect.getfile(inspect.currentframe()).split('.py')[0]) + '_config.ini'):
    parser = configparser.ConfigParser()
    if os.path.exists(config_file_path):
        with open(config_file_path, 'r') as config_file:
            parser.read(config_file)
            return parser
    else:
        print('FAILED TO GET CONFIG')
        sys.exit()

def set_config(parser, config_file_path):
    if os.path.exists(config_file_path):
        with open(config_file_path, 'w') as config_file:
        parser.write(config_file) …
Run Code Online (Sandbox Code Playgroud)

python configparser python-3.x

5
推荐指数
1
解决办法
3829
查看次数