5

the situation is:

python embed in ios app (libpython2.7.a), all logic is writed by python, some api support to call though swig wrap, if the python is py(c,o) everything is ok but too slow, i want to speed up than i use cython compile to .c source than .so, it seem load but

can't find "__ file __" define

here is the call stack:

[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)

]

the python source is:

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

what's the problem, how to fix it?

Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
sentball
  • 51
  • 1
  • 2

2 Answers2

4

It is intended behaviour, as __file__ is not defined for compiled executable. You should check for that case with

getattr(sys, 'frozen', False)

and act accordingly, for example:

if getattr(sys, 'frozen', False):
    __file__ = os.path.dirname(sys.executable)
alko
  • 46,136
  • 12
  • 94
  • 102
1

If you only need to get a package root path in Cython module, but __file__ is not defined due to the Python bug http://bugs.python.org/issue13429, then you can use a simple trick by referencing __init__.py:

def get_package_root():
    from . import __file__ as initpy_file_path
    return os.path.dirname(init‌​py_file_path)
Vlad Frolov
  • 7,445
  • 5
  • 33
  • 52
  • in python 3.6.1 this does not work either. Reports an error: ```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 Jul 12 '17 at 13:51