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__?

3
  • 1
    What do you use it for?
    – poke
    Oct 7, 2013 at 12:43
  • __file__ does now work on recent versions of Cython (>0.27) when run on Python 3.5+.
    – DavidW
    Sep 29, 2020 at 20:35
  • __file__ gives me "built-in" instead of the filename in Cython >0.29 on Python 3.7.0
    – JacKeown
    Oct 7, 2020 at 14:23

3 Answers 3

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())
4
  • 4
    That only works for Python code stack frames, not for C extensions.
    – Martijn Pieters
    Oct 7, 2013 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 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) Aug 16, 2016 at 13:01
  • @MartijnPieters what is your suggestion for C extensions?
    – denfromufa
    Jul 25, 2017 at 4:35
  • This answer didn't work correctly for me, it was returning cwd, while Vlad Frolov answer did the job!
    – SuperGeo
    May 29, 2018 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.

0

why not use sys.argv[0] ?

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

1
  • 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 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.