python导入语句遇到了一些奇怪的东西。在
假设我的文件结构如下:foo\
__init__.py
bar.py
os.py
代码输入棒.py(其他文件为空)
^{pr2}$
奇怪的是当我运行python -m foo.bar时,它会打印出来foo/os.pyc
但是,当我将direcotry改为foo,并运行python -m bar时,它会打印出来/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc
我运行脚本的两种方式有什么区别?
总之,Python导入模块的顺序是什么?
从官方文件中,我发现了一些关于这个问题的文字(它们使我更加困惑)the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.In fact, such references are so common that the import statement first looks in the containing package before looking in the standard module search path.
...
If the imported module is not found in the current package (the package of which the current module is a submodule), the import statement looks for a top-level module with the given name.