假设您的两个目录都是真正的Python包(其中包含__init__.py文件),这里是一个安全的解决方案,可以将模块相对于脚本的位置包含在内.
我假设您要这样做,因为您需要在脚本中包含一组模块.我在几个产品的生产中使用它,并在许多特殊情况下工作,例如:从另一个目录调用的脚本或用python执行而不是打开新的解释器.
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# Use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if the script is called in different ways on Windows.
# __file__ fails if someone does os.chdir() before.
# sys.argv[0] also fails, because it doesn't not always contains the path.
作为奖励,这种方法可以让您强制Python使用您的模块而不是系统上安装的模块.
警告!当前模块在egg文件中时,我真的不知道发生了什么.它可能也失败了.