0

常规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(工作)

酒吧.py

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

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

扩展名.py

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

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

当前的解决方法

扩展名.py

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

1 回答 1

0

The answer below is for revision 1 of this question

It worked for me:

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

'__file__' works for me as well.

于 2016-11-10T09:56:57.390 回答