Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python '__file__' is not defined [duplicate]

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?

like image 399
sentball Avatar asked Oct 28 '13 09:10

sentball


2 Answers

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)
like image 70
alko Avatar answered Sep 20 '22 21:09

alko


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)
like image 29
Vlad Frolov Avatar answered Sep 19 '22 21:09

Vlad Frolov