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

Pet*_* E. 6 deep-copy configparser python-2.7

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

http://bugs.python.org/issue16058

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

非常感谢,-Pete

Toe*_*nex 7

这只是Jan Vlcinsky用Python 3编写的答案的一个示例实现(我没有足够的声誉将此作为对Jans答案的评论发布).非常感谢Jan为正确的方向努力.

为了使全(深)复制base_confignew_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)
Run Code Online (Sandbox Code Playgroud)


Cha*_*les 5

基于@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)
Run Code Online (Sandbox Code Playgroud)