刚刚开始我的Python学习曲线,在将一些代码移植到Python2.7时遇到了一些障碍。在Python2.7中,似乎不再可能在ConfigParser实例上执行深度复制()。看起来Python团队对恢复这样的功能也不是特别感兴趣:
http://bugs.python.org/issue16058
有人能提出一个优雅的解决方案来手动构建ConfigParser实例的深度副本/副本吗?
非常感谢,-Pete
发布于 2015-08-29 22:50:58
基于@Toenex答案,针对Python 2.7进行了修改:
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)
发布于 2014-06-21 23:51:52
这只是一个用Python3编写的Jan Vlcinsky answer的示例实现(我没有足够的名气将其作为对Jans answer的评论)。非常感谢Jan在正确的方向上的推动。
要将base_config
完整(深度)复制到new_config
中,只需执行以下操作;
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)
发布于 2021-05-17 15:35:05
如果您使用的是Python3 (3.2+),则可以使用Mapping Protocol Access将源配置的部分和选项复制(实际上是深度复制)到另一个ConfigParser对象。
您可以使用read_dict()
复制配置解析器的状态。
这是一个演示:
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"
要显示结果配置,您可以尝试:
import io
output = io.StringIO()
dst_cfg.write(output)
print(output.getvalue())
你会得到:
[Section A]
key1 = value1
key2 = value2
[Section B]
key3 = value3
https://stackoverflow.com/questions/23416370
复制相似问题