首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python2.7中手动构建ConfigParser的深层副本

在Python2.7中手动构建ConfigParser的深层副本
EN

Stack Overflow用户
提问于 2014-05-02 04:50:15
回答 3查看 2.4K关注 0票数 9

刚刚开始我的Python学习曲线,在将一些代码移植到Python2.7时遇到了一些障碍。在Python2.7中,似乎不再可能在ConfigParser实例上执行深度复制()。看起来Python团队对恢复这样的功能也不是特别感兴趣:

http://bugs.python.org/issue16058

有人能提出一个优雅的解决方案来手动构建ConfigParser实例的深度副本/副本吗?

非常感谢,-Pete

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-29 22:50:58

基于@Toenex答案,针对Python 2.7进行了修改:

代码语言:javascript
复制
import StringIO
import ConfigParser

# Create a deep copy of the configuration object
config_string = StringIO.StringIO()
base_config.write(config_string)

# We must reset the buffer to make it ready for reading.        
config_string.seek(0)        
new_config = ConfigParser.ConfigParser()
new_config.readfp(config_string)
票数 5
EN

Stack Overflow用户

发布于 2014-06-21 23:51:52

这只是一个用Python3编写的Jan Vlcinsky answer的示例实现(我没有足够的名气将其作为对Jans answer的评论)。非常感谢Jan在正确的方向上的推动。

要将base_config完整(深度)复制到new_config中,只需执行以下操作;

代码语言:javascript
复制
import io
import configparser

config_string = io.StringIO()
base_config.write(config_string)
# We must reset the buffer ready for reading.
config_string.seek(0) 
new_config = configparser.ConfigParser()
new_config.read_file(config_string)
票数 7
EN

Stack Overflow用户

发布于 2021-05-17 15:35:05

如果您使用的是Python3 (3.2+),则可以使用Mapping Protocol Access将源配置的部分和选项复制(实际上是深度复制)到另一个ConfigParser对象。

您可以使用read_dict()复制配置解析器的状态。

这是一个演示:

代码语言:javascript
复制
import configparser

# the configuration to deep copy:
src_cfg = configparser.ConfigParser()
src_cfg.add_section("Section A")
src_cfg["Section A"]["key1"] = "value1"
src_cfg["Section A"]["key2"] = "value2"

# the destination configuration
dst_cfg = configparser.ConfigParser()
dst_cfg.read_dict(src_cfg)
dst_cfg.add_section("Section B")
dst_cfg["Section B"]["key3"] = "value3"

要显示结果配置,您可以尝试:

代码语言:javascript
复制
import io

output = io.StringIO()
dst_cfg.write(output)
print(output.getvalue())

你会得到:

代码语言:javascript
复制
[Section A]
key1 = value1
key2 = value2

[Section B]
key3 = value3
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23416370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档