【问题标题】:Python Identify File Path to ModulePython识别模块的文件路径
【发布时间】:2016-11-10 09:40:00
【问题描述】:

常规的os.path.dirname(__file__) 在我目前所处的特殊环境中不起作用。我希望这不会产生影响,但它是 Jython 2.7。

text_dir = os.path.dirname(__file__)
NameError: global name '__file__' is not defined

如果我从函数内部调用os.path.dirname(__file__),它就可以正常工作。

版本 1(有效)

bar.py

import os
def bar():
  location = os.path.dirname(__file__)
  return location

第 2 版(不起作用,见上面的 NameError)

extension.py

import os
from some_tool import Extensions
class extended(Extensions):
  def foo():
    location = os.path.dirname(__file__)

知道为什么吗?它与Jython有关吗?还是因为它在class 内?还是因为它继承了某些东西?

当前解决方法

extension.py

import bar
from some_tool import Extensions
class extended(Extensions):
    def foo():
        location = bar.bar()

【问题讨论】:

  • __file__ 中的引号字符不是不必要的吗?
  • @pt12lol 他们没有必要,他们错了。
  • 我检查了这两个选项,似乎都适用于我的本地。
  • 'both' 我的意思是带引号和不带引号。没有人提到/opt/process。
  • @pt12lol '__file__' 只是一个普通字符串,如果你尝试'thisfiledoesnotexist',你会得到相同的结果。 __file__ 不带引号是一个“神奇”变量,Python 会将其设置为当前模块的文件名。

标签: python module jython-2.7 sys.path


【解决方案1】:

下面的答案是revision 1 of this question

它对我有用:

 $ pwd
/tmp
 $ cat test.py
import os; print(os.path.dirname(os.path.realpath(__file__)))
 $ python test.py
/tmp

'__file__' 也适用于我。

【讨论】:

  • 这与问题有什么关系?它本质上是关于进口的,尽管标题可能具有误导性。
  • 我明白了——现在又变了——我的借口。
  • @Isaac(以及任何访问此问题或仅对此感兴趣的人):我问here 在这种情况下该怎么办并得到a great answer。
猜你喜欢
  • 2019-10-21
  • 2021-05-12
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多