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

[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. 扩大默认的模块搜索路径。





Stay hungry, stay foolish.


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

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.