根據(jù)例子逐個分析
導(dǎo)入下一層目錄中的文件
-
補(bǔ)充
__all__變量作用
我們可以在某級目錄的__init__.py里設(shè)置__all__參數(shù),當(dāng)from m import *時,*能導(dǎo)入的內(nèi)容就是__all__參數(shù)的值。
例如,我們在effects.__init__.py中寫下如下代碼,只載入模塊surround和下級文件夾third,而沒有包含模塊echo:
__all__ = ['surround', 'third']
再在test_main.py中,分別調(diào)用surround、third.third1和echo的test()函數(shù):
from effects import *
surround.test()
third.third1.test()
echo.test()
運(yùn)行結(jié)果,surround、third.third1均調(diào)用成功,而echo拋出異常。
Traceback (most recent call last):
============== surround.test ==============
============== chird1.test ==============
File "E:\WorkSpace\Python\test\sound\test_main.py", line 11, in <module>
echo.test()
NameError: name 'echo' is not defined
[Finished in 0.2s with exit code 1]
調(diào)用平級目錄下的模塊
- 這種調(diào)用官方說明給出的方法是直接通過
from import來調(diào)用。
例如:在我們一直使用的例子中,sound是工程的最高一層目錄,effects和formats是sound下的兩個目錄。
想在effects.echo中調(diào)用formats.wavread的test(),添加如下代碼:
# 導(dǎo)入平級目錄下的模塊
from sound.formats import wavread
# 調(diào)用評級目錄下模塊的函數(shù)
wavread.test()
在Pycharm的工程中運(yùn)行正常,但如果用命令行執(zhí)行,則會報錯:
Traceback (most recent call last):
File "E:\WorkSpace\Python\test\sound\effects\echo.py", line 4, in <module>
from sound.formats import wavread
ImportError: No module named sound.formats
[Finished in 0.2s with exit code 1]
-
問題出錯的原因,回頭看一下官方指導(dǎo)對于路徑搜素的說明就清楚了。
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.pathis 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 variablePATH). - the installation-dependent default.
After initialization, Python programs can modifysys.path.
查找模塊的搜索,簡單的說就是在sys.path的列表目錄里搜索,包括python的bulid-in模塊、第三方模塊(在python下的\Lib\site-packages\目錄下)。但是,我們自己創(chuàng)建的工程,實際上不在python的搜索目錄下,所以找不到會報錯。
至于Pycharm運(yùn)行沒有問題,是因為IDE在運(yùn)行時,默認(rèn)把工程目錄加入了sys.path。
我們可以用sys.path.append(path)的方法,將工程目錄加入運(yùn)行時環(huán)境,這樣就可以讓代碼成功執(zhí)行。
# 修改sys.path
import sys
sys.path.append('E:\\WorkSpace\\Python\\test\\')
# 導(dǎo)入平級目錄下的模塊
from sound.formats import wavread
運(yùn)行結(jié)果:
============== 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,那么在導(dǎo)入時只需from formats import wavread即可。
真正的工程項目,應(yīng)該不需要在代碼中導(dǎo)入,可能需要在安裝時設(shè)置變量。這個就留到發(fā)布時再研究吧。