I have a file package.py
that i am trying to package into package.pyd
. I have the following statement in package.py
CURR = os.path.dirname(os.path.realpath(__file__))
which works fine when I run package.py
but when I import package.pyd
into another file wrapper.py
I get the following error message
Traceback (most recent call last):
File "C:\Projects\Wrapper.py", line 1, in <module>
import package
File "package.py", line 40, in init package (package.c:4411)
NameError: name '__file__' is not defined
How can I get the location of the .pyd file. Also is there a way to check if it is being run as a .pyd or .py.
Thank you!
It seems that __file__ variable not available in module init. But you can get
__file__
after module was loaded:You can check the
__file__
variable to know what file was loaded. Also keep in mind python's search order:pyd (so), py, pyw(for windows), pyc
.More information about it is in this this question
Found two working methods.
Involving inspect module:
import
some file from the same level and using its__file__
attribute:Actually, it doesn't have to be
__init__.py
module, you can add and import any [empty] file to make it work.