【问题标题】:python '__file__' is not defined [duplicate]python'__file__'未定义[重复]
【发布时间】:2013-10-28 09:03:14
【问题描述】:

情况是:

python 嵌入到 ios 应用程序(libpython2.7.a)中,所有逻辑都由 python 编写,一些 api 支持通过 swig wrap 调用,如果 python 是 py(c,o) 一切没关系,但是太慢了,我想加快速度,而不是使用 cython 编译到 .c 源而不是 .so,它似乎加载但

找不到“__文件__”定义

这里是调用栈:

[CGPLoad.py] load from file error [Error Message:

exceptions.NameError:name '__ file __' is not defined

Traceback:

init CGPLoad (build/CGPLoad.c:3054): CGPLoad.py(# 19)

init LogInOutShell (build/LogInOutShell.c:3089): LogInOutShell.py(# 20)

init CommonToolShell (build/CommonToolShell.c:6560): CommonToolShell.py(# 19)

init GameWorld (build/GameWorld.c:2516): GameWorld.py(# 19)

init IPY_GAMEWORLD (build/IPY_GAMEWORLD.c:27700): IPY_GAMEWORLD.py(# 28)

IPY_GAMEWORLD.swig_import_helper (build/IPY_GAMEWORLD.c:4304): IPY_GAMEWORLD.py(# 18)

]

python源码是:

fp, pathname, description = imp.find_module('_IPY_GAMEWORLD', [dirname(__ file __)])

什么问题,如何解决?

【问题讨论】:

  • 看起来__FILE 之间有空格。
  • er...如果靠近它不能显示“”,它是“__file

标签: python c python-2.7


【解决方案1】:

这是预期的行为,因为__file__ 没有为已编译的可执行文件定义。您应该使用

来检查这种情况
getattr(sys, 'frozen', False)

并采取相应的行动,例如:

if getattr(sys, 'frozen', False):
    __file__ = os.path.dirname(sys.executable)

【讨论】:

【解决方案2】:

如果你只需要在 Cython 模块中获取一个包根路径,但由于 Python 错误http://bugs.python.org/issue13429 而没有定义__file__,那么你可以通过引用__init__.py 来使用一个简单的技巧:

def get_package_root():
    from . import __file__ as initpy_file_path
    return os.path.dirname(init‌​py_file_path)

【讨论】:

  • 在 python 3.6.1 中这也不起作用。报错:Traceback (most recent call last): File "main.py", line 94, in init main (..\..\main.c:3617) File "main.py", line 6, in main.get_package_root (..\..\main.c:1237) super().__init__(ismain=True, uni_theme=True) ImportError: cannot import name __file__
猜你喜欢
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2014-05-27
相关资源
最近更新 更多