NrNazifi
NrNazifi

Reputation: 1651

What method can I use instead of __file__ in python?

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

Upvotes: 17

Views: 3863

Answers (3)

Carl Cheung
Carl Cheung

Reputation: 558

why not use sys.argv[0] ?

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

Upvotes: 0

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())

Upvotes: 13

Steve Barnes
Steve Barnes

Reputation: 28405

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.

Upvotes: 0

Related Questions