python 系统属性“__file__”在不同 linux 发行版上不一致

Inconsistency in python system attribute "__file__" on different linux distros

我正在处理奇怪的问题。考虑这个简单的代码:

print(__file__)
print("***" + os.path.dirname(__file__) + "###")

现在当我 运行 我的笔记本电脑上有 Fedora 23 OS 时,输出是:

/home/.../ExperimentalSystem/BullshitSetupGenerator.py
***/home/.../ExperimentalSystem###

运行在 Ubuntu 15.10:

上使用相同的代码
BullshitSetupGenerator_delete_me.py
***###

谁能解释一下为什么?我错过了什么吗?

您可能不想完全依赖 __file__ 属性,但您要确保拥有完整路径 abspath:

os.path.dirname(os.path.abspath(__file__))

__file__ 由提供给 Python 的参数定义,该参数告诉它您的文件是什么。例如,假设您位于名为 Here 的文件夹中。你可以说 python ../Here/here.py__file__ 就是 ../Here/here.py。如果 运行 同一个文件只有 python here.py__file__ 就是 here.py。当您 运行 同一目录中的 Python 文件而不使用绝对路径或奇怪的相对路径时,该文件将不会提及任何目录。这意味着 os.dirname(__file__) 将是空白的。如果需要,可以使用 os.path.abspath().

获取绝对路径