python引用其他目录的模块

在python中,比如在$project_dir/demo.py中想使用 $project_dir/lib/mylib.py这个module,那么可以通过如下两个方法来实现:
1. 将lib作为package,在demo.py中通过 "import lib.mylib as mylib"这样来导入所需的module。
这时,可能遇到pyton并没有将lib作为package来使用,从而没有找到mylib这个module,这时需要在$project_dir/lib/目录下添加 __init__.py文件(文件内容为空即可)。
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

2. 可以直接使用 sys.path.append($project/lib)将lib目录添加到搜寻module的目录中去,然后直接 import mylib即可导入lib/mylib.py这个模块。

[update 2015.11.21]
sys.path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

PYTHONPATH Augment the default search path for module files. 扩大默认的模块搜索路径。

python脚本所在目录,是其在sys.path的第一个位置sys.path[0]的位置,之后是$PYTHONPATH设置的搜索目录,之后是python版本相关的一些搜索路径,最后是sys.path.append(mypath)添加的路径。

所以,也可以设置PYTHONPATH环境变量,如:

参考资料:
1. http://docs.python.org/2/tutorial/modules.html#packages
2. http://stackoverflow.com/questions/279237/import-a-module-from-a-folder

master

Stay hungry, stay foolish.

发表评论

邮箱地址不会被公开。 必填项已用*标注

*