How can I access the current executing module or class name in Python?

前端 未结 11 1843
醉酒成梦
醉酒成梦 2020-12-05 01:30

I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:

foo.py:

11条回答
  •  一向
    一向 (楼主)
    2020-12-05 02:32

    To obtain a reference to the "__main__" module when in another:

    import sys
    sys.modules['__main__']
    

    To then obtain the module's file path, which includes its name:

    sys.modules['__main__'].__file__
    

    If within the "__main__" module, simply use: __file__

    To obtain just the file name from the file path:

    import os
    os.path.basename(file_path)
    

    To separate the file name from its extension:

    file_name.split(".")[0]
    

    To obtain the name of a class instance:

    instance.__class__.__name__
    

    To obtain the name of a class:

    class.__name__
    

提交回复
热议问题