NameError: name '__file__' 未定义

Ang*_*uks 1 python nameerror

我正在尝试使用以下方法将脚本的路径存储到变量中:

os.path.abspath(os.path.dirname(__file__))
Run Code Online (Sandbox Code Playgroud)

但是,它不断返回name '__file__' is not defined错误。

here = os.path.dirname(os.path.abspath(__file__))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
Run Code Online (Sandbox Code Playgroud)

Yev*_*ych 6

很确定您是在交互式 Python 的终端中运行它的,因为它是唯一(我知道)没有__file__. 此外,如果它是一个脚本,并且它将是它的第一行(根据错误消息),它将失败os is not defined(因为您不会导入它)。

在实际脚本中尝试一下。这应该有效。


S3D*_*DEV 6

我在 Spyder 中测试/调试类时(几乎每天)都会遇到这个问题。修复很简单:将__file__变量定义为您正在测试的 py 模块的名称。

在解释器中输入:

__file__ = 'modulename.py'
Run Code Online (Sandbox Code Playgroud)

然后再次运行该脚本。这种方法从来没有给我带来问题。