问题
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