python使用其他目录中的module

在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这个模块。

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


相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...