Python packages not originating from filesystem

假装没事ソ 提交于 2019-12-10 15:42:42

问题


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

[...] You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. [...]

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

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?


回答1:


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.

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!


来源:https://stackoverflow.com/questions/46994125/python-packages-not-originating-from-filesystem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!