问题
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!
回答1:
It seems that __file__ variable not available in module init.
But you can get __file__
after module was loaded:
def get_file():
return __file__
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 inspect import sys import os if hasattr(sys.modules[__name__], '__file__'): _file_name = __file__ else: _file_name = inspect.getfile(inspect.currentframe()) CURR = os.path.dirname(os.path.realpath(_file_name))
import
some file from the same level and using its__file__
attribute:import os from . import __file__ as _initpy_file CURR = os.path.dirname(os.path.realpath(_initpy_file))
Actually, it doesn't have to be
__init__.py
module, you can add and import any [empty] file to make it work.
回答2:
__file__
now works in recent more versions of Cython (0.27 ish) when on run on a version of Python that supports multi-phase module initialization (Python >=3.5). See https://github.com/cython/cython/issues/1715 for the point at which it was added.
来源:https://stackoverflow.com/questions/40857480/how-to-get-path-of-the-pyd-file-aka-equivalent-of-file