17

I convert my python code to c by cython and after that compile .c file and use .so in my project. My problem: I use __file__ in my python code and in while compile by gcc, it doesn't get error. but when I run program and import .so in other python files, appear an error from __file__ line.

How can solve this problem? Is there any method to replace with __file__?

Wooble
  • 87,717
  • 12
  • 108
  • 131
NrNazifi
  • 1,621
  • 3
  • 25
  • 36

3 Answers3

13

Try to add this at the beginning of your file:

import inspect
import sys
if not hasattr(sys.modules[__name__], '__file__'):
    __file__ = inspect.getfile(inspect.currentframe())
ethanhs
  • 1,483
  • 9
  • 12
  • 4
    That only works for Python code stack frames, **not** for C extensions. – Martijn Pieters Oct 07 '13 at 12:49
  • 8
    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(initpy_file_path)` – Vlad Frolov Aug 16 '16 at 13:01
  • @MartijnPieters what is your suggestion for C extensions? – denfromufa Jul 25 '17 at 04:35
  • This answer didn't work correctly for me, it was returning cwd, while Vlad Frolov answer did the job! – SuperGeo May 29 '18 at 18:51
0

Not too sure how you will make it python compatible but gcc #defines __FILE__ for the name of the file that the code is in.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
0

why not use sys.argv[0] ?

This works even when it's compiled into a cython executable.

Carl Cheung
  • 498
  • 5
  • 8
  • 1
    But doesn't work in any other case. You're often using `__file__` to work out where a module is installed – DavidW Apr 24 '23 at 05:23