2012-10-26 46 views
3

想象一下,我有一个脚本,假设我导入为模块的my_tools.py。但是my_tools.py会保存两次:C:\Python27\Lib 并且位于执行导入的脚本所在的同一目录中。我可以改变python首先查找模块的顺序吗?

我可以更改python先查找my_tools.py的顺序吗?也就是说,首先检查它是否存在于C:\Python27\Lib,如果是,请执行导入?

+0

默认情况下'import'将首先在当前工作目录中查找,然后转到sys.path中指定的路径 – avasal

+0

是的,我知道。我的问题是:可以改变这个? – LarsVegas

+0

嗯,这是用例:我有一个脚本,我私下使用不同的Python版本比网络上的其他人。所以我希望能够使用不同版本的导入模块。 – LarsVegas

回答

2

您可以修改sys.path,它将确定Python搜索导入的顺序和位置。 (请注意,你必须这样做之前 import语句。)

2

如果你不想python搜索内置模块那么当前文件夹先在搜索,,

你可以改变sys.path

upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter

sys.path[0] is the empty string, which directs Python to search modules in the current directory first,您可以在列表的末尾把这个,这样它会前在所有可能的位置首先搜索来到当前目录

相关问题