简体   繁体   English

python 是否支持*导入* gzip 文件?

[英]Is there support in python to *import* a gzipped file?

Assuming I have a gzipped mymodule.py.gz I hoped that python (maybe with some parameters) could import it with:假设我有一个 gzipped mymodule.py.gz我希望 python(可能有一些参数)可以导入它:

import mymodule

(I would imagine that when a.py file is not found, then.py.gz is looked for.) (我想当找不到 a.py 文件时,就会查找 then.py.gz。)

or maybe there is a specific version of import:或者可能有特定版本的导入:

gzimport mymodule

I would not want to uncompress the file if possible.如果可能的话,我不想解压缩文件。 I guess, I could just uncompress it (from within python maybe to /tmp) and import it as normal.我想,我可以解压缩它(从 python 中可能到 /tmp)并正常导入它。 But I would rather not do that if I do not have to.) Other compression formats would also be of interest.但如果不是必须的话,我宁愿不这样做。)其他压缩格式也很有趣。

Since you mentioned " other compression formats would also be of interest ":既然你提到“其他压缩格式也会感兴趣”:

This actually works out of the box for.zip format.这实际上适用于 .zip 格式。 You just need to have the zipfile on the sys.path (just the same as any other directory containing.py files available for importing).您只需要将 zip 文件放在sys.path上(就像任何其他包含可用于导入的 .py 文件的目录一样)。

$ echo 'print("hello world")' > mymodule.py
$ zip -o example.zip mymodule.py 
  adding: example.py (stored 0%)
$ rm mymodule.py 
$ python3
Python 3.10.2 (main, Feb  2 2022, 06:19:27) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append("example.zip")
>>> import mymodule
hello world

It works because there is a zipimporter active by default:它之所以有效,是因为默认情况下有一个zipimporter处于活动状态:

>>> mymodule
<module 'mymodule' from 'example.zip/mymodule.py'>
>>> mymodule.__loader__
<zipimporter object "example.zip/">

To get it working for.gz format, you could add support fairly easily by adding a gzip importer to the sys.meta_path .要使其适用于 .gz 格式,您可以通过将 gzip 导入器添加到sys.meta_path来相当轻松地添加支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM