【问题标题】:Python & Eclipse - Get curent filename errorPython & Eclipse - 获取当前文件名错误
【发布时间】:2013-10-08 13:21:46
【问题描述】:

我决定开始使用 Eclipse 在 python 中编写代码,但是我在获取当前脚本的文件名时遇到了问题。要获取我使用的当前文件名:

#!/usr/bin/env python2.7
import os
os.path.basename(__file__)

我的代码在使用 bash 终端或 Geany 时可以完美运行,但使用 Eclipse 交互式控制台我得到:

 name '__file__' is not defined

有什么想法吗?

更新

当我使用 python filename.py 运行我的代码时,它运行良好,但是当我尝试从 python 或 ipython 控制台运行它时,我得到了同样的错误

【问题讨论】:

  • 尝试在代码中的某处设置断点并进行调试。在调试控制台中检查__file__,看看它是否有效
  • 从交互式控制台运行其他 python 代码是否有效?
  • @jorgehumberto 是否还有其他魔法变量有效?
  • @jorgehumberto 还是您在 Eclipse 中使用标准的 Python 解释器?
  • @inspectorG4dget 不,什么都没有,它只是终止了,我在变量 'file' 上什么也没得到

标签: eclipse python-2.7 filenames os.path


【解决方案1】:

好的,找到了与 PyDev 的交互式控制台一起使用的替代方法:

How to properly determine current script directory in Python?

解决办法是:

#!/usr/bin/env python2.7
import inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename.split('/')[-1]

【讨论】:

    猜你喜欢
    • 2012-12-21
    • 2013-10-31
    • 2011-05-12
    • 2011-08-18
    • 2010-10-26
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多