问题
I have created a folder named "custom_module" and I have the __init__.py inside the folder which contains:
__all__ = [
'Submodule1',
'Submodule2'
]
From what documentation I read I should be able to call import custom_module
and get access to the package, however this isn't happening. How can I make python recognize my package? I am using python 3.2
Update: The package is not located in the python folder. How does the python environment find it, so I can successfully import it by name.
回答1:
sys.path
holds the Python search path. Before trying to import
your modules and packages, set it to include your path:
import sys
sys.path.insert(0, 'your_path_here')
import custom_module
More detail in the Python docs and in this question
回答2:
There are two distinct concepts you are confusing: packages and modules.
A module is what you think it is: a Python script containing classes, variables, whatever. You import it by its filename, and can then access the variables in its namespace.
A package is a collection of modules which are grouped together inside a folder. If the folder contains a file called __init__.py
, Python will allow you to import the entire folder as if it were a module. This will run the code in __init__
, but will not necessarily import all of the modules in the folder. (This is a deliberate design choice: packages are often very large, and importing all of the modules could take a very long time.)
The only things which are exported (as package.thing
) by default are the variables defined inside __init__
. If you want submodule
to be available as package.submodule
, you need to import it inside __init__
.
__all__
is a related concept. In brief, it defines what is imported when you do from package import *
, because it's not easy for Python to work out what that should be otherwise. You don't in general need it.
来源:https://stackoverflow.com/questions/12475678/how-to-import-custom-python-package-by-name