PythonTip >> 博文 >> iteye


zihua 2013-10-10 15:10:10 点击: 955 | 收藏

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


作者:zihua | 分类: iteye | 标签: python | 阅读: 955 | 发布于: 2013-10-10 15时 |