使用zipimport的正确方法; "zipimport.ZipImportError: not a Zip file"看似有效的文件



>我已经设法在没有安装的情况下使用了这个模块 - 只需从路径导入它即可使用 ,

import sys 
url = 'https://example.com' 
sys.path.insert(0, r'C:UsersiDownloadsyou-get-0.4.1128src')  # 
from you_get import common 
common.any_download(url, info_only=True)#NoneType 

似乎可以在Python中使用zipimport直接使用模块的zip存档而无需提取,我想知道使用zipimport的正确方法是什么,像下面这样的简单尝试只是给出了例外。我从这里下载了文件,文件C:UsersiDownloadsyou-get-0.4.1128.zip确实存在并且没有损坏。

>>> import zipimport 
>>> zipimport.zipimporter(r'C:UsersiDownloadsyou-get-0.4.1128.zip') 
Traceback (most recent call last): 
File "<pyshell#1>", line 1, in <module> 
zipimport.zipimporter(r'C:UsersiDownloadsyou-get-0.4.1128.zip') 
zipimport.ZipImportError: not a Zip file: 'C:\Users\i\Downloads\you-get-0.4.1128.zip' 
>>> 

(这是回答您的问题的建议操作方式:"使用zipimport的正确方法";有关错误的直接原因,请参阅下文。

您不应直接使用zipimport。相反,您应该将.zip文件添加到sys.path- 它将像目录一样使用。

也就是说,您下载的文件是一个源代码分发- 它在root中有一个setup.py,并且在子目录中具有实际模块。要使用该模块,您需要一个构建的发行版。

讲述源代码和构建发行版的所有信息超出了单一答案的范围。一种可能的方法是:

  • 打开.zip
  • 使用带有python setup.py bdist_wheelsetup.py制作轮子
  • 使用pip install <path to .whl>安装它

Debugging with Visual Studio 显示这是它阻塞的代码:

v3.6.5Moduleszipimport.c

if (fseek(fp, -22, SEEK_END) == -1) {
<...>
}
header_position = (unsigned long)ftell(fp);
<...>
if (fread(buffer, 1, 22, fp) != 22) {
<...>
}
if (get_uint32(buffer) != 0x06054B50u) {
/* Bad: End of Central Dir signature */
errmsg = "not a Zip file";
goto invalid_header;
}

如您所见,它读取并验证文件的最后 22 个字节作为"中央目录签名的结尾"。

规范说:

4.3.1 ZIP 文件必须包含"中央目录记录的末尾"。

<...>

4.3.6 总体.ZIP文件格式:

<...>
[end of central directory record]

4.3.16 中央目录记录结束:

end of central dir signature    4 bytes  (0x06054b50)
number of this disk             2 bytes
number of the disk with the
start of the central directory  2 bytes
total number of entries in the
central directory on this disk  2 bytes
total number of entries in
the central directory           2 bytes
size of the central directory   4 bytes
offset of start of central
directory with respect to
the starting disk number        4 bytes
.ZIP file comment length        2 bytes
.ZIP file comment       (variable size)

如您所见,此"中央目录记录的结尾"是 22 个字节。没有评论。这个文件确实有一个注释:

$ xxd -s 0x322b5 -g 1 you-get-0.4.1128.zip
000322b5: 50 4b 05 06 00 00 00 00 af 00 af 00 25 45 00 00  PK..........%E..
000322c5: 90 dd 02 00 28 00 61 30 62 39 37 65 35 36 65 35  ....(.a0b97e56e5
000322d5: 36 35 38 36 33 35 62 35 63 35 66 32 66 33 32 65  658635b5c5f2f32e
000322e5: 38 62 38 63 31 34 62 64 33 35 61 65 62 33        8b8c14bd35aeb3

所以这是一个错误。这是一张相关的票证。

我已经下载了该文件并有相同的异常,尽管文件似乎是合法的。

也许你应该改用zipfile

>>> import zipfile
>>> zipfile.ZipFile( 'you-get-0.4.1128.zip' )
<zipfile.ZipFile object at 0x7fc515343c50>
>>>

最新更新