How to get path of the pyd file aka equivalent of

2019-07-22 09:32发布

问题:

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.

  1. 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))
    
  2. 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.