Python软件包不是源自文件系统 [英] Python packages not originating from filesystem

查看:49
本文介绍了Python软件包不是源自文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在描述导入系统的python 文档中,有以下内容(我强调):

In the python documentation describing the import system, there is the following (emphasis done by me):


[...]您可以将包视为文件系统上的目录,并将模块视为文件在目录中,但是请不要从字面上看这样的类比,因为程序包和模块不必源自文件系统。 [...]

有哪些选项可用于分别存储与文件和文件夹不对应的模块和软件包。文件系统?

What options are there for storing modules and packages that do not correspond to files and folders, respectively, in the filesystem?

阅读关于从zip归档文件加载模块和软件包的可能性。这是引用段落所引用的可能选项之一吗?
还有其他这样的选择吗?

I read about the possibility of loading modules and packages from zip archives. Is this one of the possible options that the quoted paragraph refers to? Are there any other such options?

推荐答案

这是您可以考虑软件包和模块的方式,但并非强制要求软件包/模块是文件系统中的目录/文件。

That is the way you can think about packages and modules but it is not mandatory that a package/module is a directory/file in file system.

您可以将软件包/模块存储在zip文件中,然后

You can store a package/module in a zip file and load it with zipimport.

您可以从字符串变量中加载模块:

You can load a module from a string variable:

import imp

code = """
def test():
    print "function inside module!"
    """

# give module a name
name = "mymodule"
mymodule = imp.new_module(name)
exec code in mymodule.__dict__

>>> mymodule.test()
function inside module!

这篇关于Python软件包不是源自文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆