https://docs.python.org/3/tutorial/modules.html
当使用import导入后,module里的内容会自动运行
当我们run一个module时,__name__会变成__main__
if __name__ == "__main__": import sys fib(int(sys.argv[1]))1)首先查询built-in 2)查询sys.path sys.path包含了当前路径,PYTHONPATH 来添加指定路径下的模块,sys.path.append('/ufs/guido/lib/python')
To speed up loading modules, Python caches the compiled version of each module in the pycache directory under the name module.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as pycache/spam.cpython-33.pyc. This naming convention allows compiled modules from different releases and different versions of Python to coexist.
假设我们有一个处理声音的package,里面包含了format,effects,filters三个子package,每个package中又有不同的mudule __init__.py将一个directories贬称搞一个package,可以为空,可以做初始化
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ...直接导入一个module
import sound.effects.echo sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)使用from简化
from sound.effects import echo echo.echofilter(input, output, delay=0.7, atten=4)from也可以导入一个具体的函数,类和变量,但是from..import不能导入package和module
from sound.effects.echo import echofilter echofilter(input, output, delay=0.7, atten=4)If all is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace
__all__ = ["echo", "surround", "reverse"]如果sound.filters.vocoder想要使用sound.effects package中的echomodule,可以使用
from sound.effects import echo当然也可以使用相对的路径
from . import echo from .. import formats from ..filters import equalizer