:\Pro-files\workspace\myPython\com\homer>python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
此时如果我们直接输入print(url),系统则会报错,url变量未定义:
>>> print(url)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'url' is not defined
>>>
所以我们需要先导入module_1的内容才算定义了url变量,不过要注意的是导入的模块的变量并不是定义在顶层命名空间,而是在模块的命名空间中,因此使用如下方式导入后的打印变量如下:
>>> from com.homer import module_3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pkg.module_3
因此,包目录下的__init__.py模块是必须的,但内容是可选的,可以为空内容,也可以写一些代码或作其他用途。PVM在导入某个包下的模块时会先导入这个包下的__init__.py模块,比如我们在__init__.py模块里添加内容:
print("This is __init__ module")
然后,在交互模式下重新导入这个包,则输出效果如下:
>>> from com.homer import module_3
This is __init__ module
Hello World
>>>
可见,PVM首先加载的是__init__.py模块,然后才是找该目录下的其他模块并进行加载。
>>> import module_4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named module_4报错是预料中的,因为F盘并不在python模块的搜索路径中,然后我们动态的增加这个路径到搜索模块中,再执行导入:
>>> import sys
>>> sys.path.append("F:\Pro-files\workspace\myPython")
>>> print(sys.path)
['', 'C:\\Windows\\system32\\python33.zip', 'F:\\Pro-files\\Python33\\DLLs', 'F:\\Pro-files\\Python33\\lib', 'F:\\Pro-files\\Python33', 'F:\\Pro-files
\\Python33\\lib\\site-packages', 'F:\\Pro-files\\workspace\\myPython']
>>> from com.homer import module_4
This is __init__ module
Hello world
4
>>>
首先是在sys.path中增加了F盘根目录作为搜索路径sys.path.append("F:\Pro-files\workspace\myPython"),随后的打印中可以看到确实已经被添加到sys.path中去了,然后再执行导入就会正常导入模块并执行模块中的语句了。当然,我们通过交互模式新增加的搜索路径也仅仅是在当前交互模式下有效,一旦退出了那么就就失效了。因此,我们可以根据搜索路径规则的第2步中说的来设置PYTHONPATH环境变量就可以满足不同使用情况下都可以找到模块了。