【发布时间】:2015-07-13 19:43:24
【问题描述】:
我正在创建一个从压缩文件加载和运行 python 脚本的程序。除了这些 python 脚本,我还有一个配置文件,我以前使用 configparser 从程序的未压缩版本中加载信息。
是否可以直接使用 configparser 直接读取 zip 文件中的配置文件?还是我必须将其解压缩到临时文件夹并从那里加载?
我试过直接给出路径:
>>> sysconf = configparser.ConfigParser()
>>> sysconf.read_file("compressed.zip/config_data.conf")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 691, in read_file
self._read(f, source)
File "/usr/local/lib/python3.4/configparser.py", line 1058, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: '<???>', line: 1
没用。没有惊喜。
然后我尝试使用 zipfile
>>> zf = zipfile.ZipFile("compressed.zip")
>>> data = zf.read("config_data.conf")
>>> sysconf = configparser.ConfigParser()
>>> sysconf.read_file(data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 691, in read_file
self._read(f, source)
File "/usr/local/lib/python3.4/configparser.py", line 1009, in _read
if line.strip().startswith(prefix):
AttributeError: 'int' object has no attribute 'strip'
发现也没用。
所以我求助于创建一个临时文件夹,解压缩到它,然后在那里读取 conf 文件。如果可能的话,我真的很想避免这种情况,因为 conf 文件是唯一的限制因素。我现在可以(并且正在)从 zip 文件中加载 python 模块就好了。
如果有办法将文件的原始文本直接传递给 configparser,我可以获得文件的原始文本,但搜索文档时我空手而归。
更新: 我尝试使用 stringIO 作为文件对象,它似乎有点工作。 configparser 不会拒绝它,但它也不喜欢它。
>>> zf = zipfile.ZipFile("compressed.zip")
>>> data = zf.read(config_data.conf)
>>> confdata = io.StringIO(str(data))
>>> sysconf = configparser.ConfigParser()
>>> sysconf.readfp(confdata)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 736, in readfp
self.read_file(fp, source=filename)
File "/usr/local/lib/python3.4/configparser.py", line 691, in read_file
self._read(f, source)
File "/usr/local/lib/python3.4/configparser.py", line 1058, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: '<???>', line: 1
(continues to spit out the entire contents of the file)
如果我改用 read_file,它不会出错,但也不会加载任何内容。
>>> zf = zipfile.ZipFile("compressed.zip")
>>> data = zf.read(config_data.conf)
>>> confdata = io.StringIO(str(data))
>>> sysconf = configparser.ConfigParser()
>>> sysconf.read_file(confdata)
>>> sysconf.items("General") #(this is the main section in the file)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/configparser.py", line 824, in items
d.update(self._sections[section])
KeyError: 'General'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 827, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: 'General'
【问题讨论】:
-
对于您最近的编辑,请将
str(data)替换为data.decode()。
标签: python zipfile configparser