Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What method can I use instead of __file__ in python?

Tags:

python

cython

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

like image 272
NrNazifi Avatar asked Oct 07 '13 12:10

NrNazifi


People also ask

What does __ FILE __ do in Python?

The __file__ variable: __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system.

How do I get the path of a file in Python?

To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you can view a particular file's path by right-clicking the File-> Properties-> General-> Location. Similarly, to run a script, the working directory needs to be set to the directory containing the script.

What is __ path __ in Python?

Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.


1 Answers

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())
like image 175
Yoann Quenach de Quivillic Avatar answered Oct 13 '22 03:10

Yoann Quenach de Quivillic