获取 Python 文件所在目录的完整路径

Get the full path to the directory a Python file is contained in

实际上,我从之前的回答中找到了我的主要问题 "Get the full path to the directory a Python file is contained in" 的解决方案:Find current directory and file's directory

如果我 运行 我的整个脚本,换句话说,热键 F5,那么答案中的下面代码就可以正常工作。

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

不过,如果我只是select上面两行代码和运行就可以了,换句话说,热键F9。然后我会收到以下错误:

NameError: name '__file__' is not defined

所以如果有人知道为什么会报错,请简单说明一下。

非常感谢!

顺便说一句,我用的是 Spyder (Python 2.7)。

在 Spyder 或任何交互式 python 进程中,常量 __file__ 未定义。

当你运行整个脚本时,Spyder基本上运行下面的命令:

$ python script.py

虽然,如果你 select 这两行,它更像是先进入一个交互式 python 过程,然后解释语句:

$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44) 
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os 
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>> 

这就是区别。