假设你的两个目录都是真正的python包(里面有__init__.py文件),这里是一个安全的解决方案,包括相对于脚本位置的模块。
我假设你想这样做,因为你需要包括一组模块与你的脚本。我在几个产品的生产中使用它,并且在许多特殊情况下工作,如:从另一个目录调用或使用python execute执行的脚本,而不是打开一个新的解释器。
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 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文件内发生了什么。也许它失败了。添加评论,如果你真的需要一个更好的解决方案,我可以投资更多的小时改善它。