根据例子逐个分析
导入下一层目录中的文件
补充__all__变量作用
我们可以在某级目录的__init__.py里设置__all__参数,当from m import *时,*能导入的内容就是__all__参数的值。
例如,我们在effects.__init__.py中写下如下代码,只载入模块surround和下级文件夹third,而没有包含模块echo:
__all__ = ['surround', 'third']
再在test_main.py中,分别调用surround、third.third1和echo的test()函数:
from effects import *
surround.test()
third.third1.test()
echo.test()
运行结果,surround、third.third1均调用成功,而echo抛出异常。
Traceback (most recent call last):
============== surround.test ==============
============== chird1.test ==============
File "E:\WorkSpace\Python\test\sound\test_main.py", line 11, in
echo.test()
NameError: name 'echo' is not defined
[Finished in 0.2s with exit code 1]
调用平级目录下的模块
这种调用官方说明给出的方法是直接通过from import来调用。
例如:在我们一直使用的例子中,sound是工程的最高一层目录,effects和formats是sound下的两个目录。
想在effects.echo中调用formats.wavread的test(),添加如下代码:
# 导入平级目录下的模块
from sound.formats import wavread
# 调用评级目录下模块的函数
wavread.test()
在Pycharm的工程中运行正常,但如果用命令行执行,则会报错:
Traceback (most recent call last):
File "E:\WorkSpace\Python\test\sound\effects\echo.py", line 4, in
from sound.formats import wavread
ImportError: No module named sound.formats
[Finished in 0.2s with exit code 1]
问题出错的原因,回头看一下官方指导对于路径搜素的说明就清楚了。
When a module named spam is imported, 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 . sys.path is initialized from these locations:
the directory containing the input script (or the current directory).
PYTHONPATH(a list of directory names, with the same syntax as the shell variable PATH).
the installation-dependent default.
After initialization, Python programs can modify sys.path.
查找模块的搜索,简单的说就是在sys.path的列表目录里搜索,包括python的bulid-in模块、第三方模块(在python下的\Lib\site-packages\目录下)。但是,我们自己创建的工程,实际上不在python的搜索目录下,所以找不到会报错。
至于Pycharm运行没有问题,是因为IDE在运行时,默认把工程目录加入了sys.path。
我们可以用sys.path.append(path)的方法,将工程目录加入运行时环境,这样就可以让代码成功执行。
# 修改sys.path
import sys
sys.path.append('E:\\WorkSpace\\Python\\test\\')
# 导入平级目录下的模块
from sound.formats import wavread
运行结果:
============== sound.__init__ ==============
============== effects.__init__ ==============
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
=======
['__builtins__', '__doc_======= formats.__init__ ==============
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'effects', 'formats']
============== wavread.py ==============_', '__file__', '__name__', '__package__', 'sys']
============== wavread.test ==============
上面是将sound的上级目录test加入到了sys.path。如果加入的路径是E:\\WorkSpace\\Python\\test\\sound,那么在导入时只需from formats import wavread即可。
真正的工程项目,应该不需要在代码中导入,可能需要在安装时设置变量。这个就留到发布时再研究吧。