假设您的两个目录都是真正的Python包(请将__init__.py),这是一个相对于脚本位置包含模块的安全解决方案。
我假设您希望这样做,因为您需要在脚本中包含一组模块。我在生产中使用这一点,并在许多特殊场景中工作,例如:从另一个目录调用的脚本或与pythonExecute一起执行的脚本,而不是打开一个新的解释器。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档案。可能也失败了。