同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
Package Import Basics
So, how do package imports work? In the place where you have been naming a simple file in your import statements, you can instead list a path of names separated by periods:
import dir1.dir2.mod
The same goes for from statements:
from dir1.dir2.mod import x
The “dotted” path in these statements is assumed to correspond to a path through the directory hierarchy on your machine, leading to the file mod.py (or similar; the extension may vary). That is, the preceding statements indicate that on your machine there is a directory dir1, which has a subdirectory dir2, which contains a module file mod.py (or similar).
Furthermore, these imports imply that dir1 resides within some container directory dir0, which is a component of the Python module search path. In other words, the two import statements imply a directory structure that looks something like this (shown with DOS backslash separators):
dir0\dir1\dir2\mod.py # Or mod.pyc, mod.so, etc.
The container directory dir0 needs to be added to your module search path (unless it’s the home directory of the top-level file), exactly as if dir1 were a simple module file.
More generally, the leftmost component in a package import path is still relative to a directory included in the sys.path module search path list we met in Chapter 21. From there down, though, the import statements in your script give the directory paths leading to the modules explicitly.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏
