What method can I use instead of __file__ in python?
Asked Answered
J

3

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

Jed answered 7/10, 2013 at 12:39 Comment(3)
What do you use it for?Radtke
__file__ does now work on recent versions of Cython (>0.27) when run on Python 3.5+.Gauvin
__file__ gives me "built-in" instead of the filename in Cython >0.29 on Python 3.7.0Demob
D
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())
Drain answered 7/10, 2013 at 12:48 Comment(4)
That only works for Python code stack frames, not for C extensions.Crissum
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)Aerothermodynamics
@MartijnPieters what is your suggestion for C extensions?Sensationalism
This answer didn't work correctly for me, it was returning cwd, while Vlad Frolov answer did the job!Klystron
U
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.

Ulla answered 7/10, 2013 at 13:4 Comment(0)
H
0

why not use sys.argv[0] ?

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

Hysteresis answered 24/4, 2023 at 2:15 Comment(1)
But doesn't work in any other case. You're often using __file__ to work out where a module is installedGauvin

© 2022 - 2024 — McMap. All rights reserved.