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#packages2. http://stackoverflow.com/questions/279237/import-a-module-from-a-folder

Original article: python使用其他目录中的module

©2014 笑遍世界. All Rights Reserved.

python使用其他目录中的module

相关文章:

你感兴趣的文章:

标签云: