Python中,'__file__'未定义。

5

现状为:

在iOS应用中嵌入Python(libpython2.7.a),所有逻辑都由Python编写,通过SWIG封装支持调用一些API。如果Python是py(c,o),一切正常但速度太慢。我想加速,于是使用Cython编译成.c源码然后再生成.so文件,它似乎被加载了,但是

找不到“__file__”定义

以下是调用堆栈:

[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 之间有空格。 - Kevin
1
如果更接近的位置无法显示“__”,那么它就是“__file__”。 - sentball
2个回答

4

这是预期的行为,因为已编译的可执行文件中未定义__file__。您应该检查是否出现了这种情况。

getattr(sys, 'frozen', False)

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

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

谢谢,我找到了这篇文章 http://bugs.python.org/issue13429 - sentball
似乎在初始化之前,.so文件使用了"file"。 - sentball

1
如果您只需要在Cython模块中获取包根路径,但由于Python bug 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__ - Andry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接