您无法直接确定正在执行的主脚本的位置 . 毕竟,有时脚本根本不是来自文件 . 例如,它可以来自交互式解释器或仅存储在存储器中的动态生成的代码 .
但是,您可以可靠地确定模块的位置,因为模块始终从文件加载 . 如果使用以下代码创建模块并将其放在与主脚本相同的目录中,则主脚本可以导入模块并使用它来定位自身 .
SOME_PATH / module_locator.py:
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
SOME_PATH / main.py:
import module_locator
my_path = module_locator.module_path()
如果在不同目录中有多个主脚本,则可能需要多个module_locator副本 .
当然,如果您的主脚本是由某些其他工具加载的,这些工具不允许您导入与您的脚本位于同一位置的模块,那么您就不走运了 . 在这种情况下,您所追求的信息根本不存在于您的程序中的任何位置 . 您最好的选择是向该工具的作者提交错误 .