【问题标题】:Inconsistency in python system attribute "__file__" on different linux distros不同Linux发行版上的python系统属性“__file__”不一致
【发布时间】:2016-07-27 17:11:48
【问题描述】:

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

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

现在,当我在装有 Fedora 23 操作系统的笔记本电脑上运行此代码时,输​​出为:

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

在 Ubuntu 15.10 上运行相同的代码:

BullshitSetupGenerator_delete_me.py
***###

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

【问题讨论】:

  • dirname函数没有不一致。不一致之处在__file__
  • dirname__file__不一致?我的猜测是后者。您是否在两个地方使用相同的相对路径运行代码?最后,为了获得一致的行为,我想你可以使用os.path.dirname(os.path.abspath(__file__))
  • 它与文件有关,是的。

标签: python linux operating-system dirname


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多